如何将非托管应用程序窗口置于前面,并使其成为(模拟)用户输入的活动窗口

我假设我需要使用pinvoke但我不确定需要哪些函数调用。

详细方案。 遗留应用程序将运行。 我将为该应用程序提供Handle。 我需要:a)将该应用程序带到顶部(在所有其他窗口的前面)。 b)使其成为活动窗口。

需要哪些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 (示例实现)。

  [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); } } 

事实certificate这非常可靠。 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);