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

问题描述 投票:13回答:3

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

场景:一个遗留应用程序将运行,我将拥有该应用程序的句柄。

我需要:

  1. 将该应用程序置于顶部(在所有其他窗口之前)
  2. 使其成为活动窗口

需要哪个Windows函数调用?

c# windows pinvoke foreground
3个回答
15
投票

如果您没有窗口的句柄,请在此之前使用它:

[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(示例实现)。


11
投票

这已被证明是非常可靠的。 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);


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

© www.soinside.com 2019 - 2024. All rights reserved.