我假设我需要使用PInvoke,但我不确定需要哪些函数调用。
情境:将运行一个旧应用程序,我将拥有该应用程序的句柄。
我需要:
- 将该应用程序置于顶部(在所有其他窗口前面)
- 使其成为活动窗口
需要哪些Windows函数调用?
我假设我需要使用PInvoke,但我不确定需要哪些函数调用。
情境:将运行一个旧应用程序,我将拥有该应用程序的句柄。
我需要:
需要哪些Windows函数调用?
如果您没有窗口的句柄,请在此之前使用以下代码:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
现在假设您已经有了应用程序窗口的句柄:
[DllImport("user32.dll", SetLastError = true)]
static extern bool SetForegroundWindow(IntPtr hWnd);
如果另一个窗口拥有键盘焦点,这将使任务栏闪烁。
如果您想强制窗口置于前台,请使用ForceForegroundWindow(示例实现)。
这被证明非常可靠。ShowWindowAsync函数专门为由不同线程创建的窗口设计。SW_SHOWDEFAULT确保在显示之前将窗口恢复,并激活。
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool ShowWindowAsync(IntPtr windowHandle, int nCmdShow);
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool SetForegroundWindow(IntPtr windowHandle);
然后进行调用:
ShowWindowAsync(windowHandle, SW_SHOWDEFAULT);
ShowWindowAsync(windowHandle, SW_SHOW);
SetForegroundWindow(windowHandle);
[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr WindowHandle);
public const int SW_RESTORE = 9;
ShowWindowAsync方法用于显示最小化的应用程序,而SetForegroundWindow方法用于将后台应用程序置于前面。
您可以像我在我的应用程序中一样使用这些方法,在按钮单击时将Skype置于我的应用程序之前。
private void FocusSkype()
{
Process[] objProcesses = System.Diagnostics.Process.GetProcessesByName("skype");
if (objProcesses.Length > 0)
{
IntPtr hWnd = IntPtr.Zero;
hWnd = objProcesses[0].MainWindowHandle;
ShowWindowAsync(new HandleRef(null,hWnd), SW_RESTORE);
SetForegroundWindow(objProcesses[0].MainWindowHandle);
}
}