15

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

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

我需要:

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

需要哪些 Windows 函数调用?

4

3 回答 3

16

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

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

于 2011-06-03T14:20:50.877 回答
13

事实证明这是非常可靠的。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);
于 2011-06-07T20:07:08.990 回答
11
    [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);
        }
    }
于 2012-01-30T05:15:14.580 回答