SetForegroundWindow()前置窗口失败的问题 - zLulus/My_Note GitHub Wiki

生效条件(任一满足)

The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:

The process is the foreground process.
The process was started by the foreground process.
The process received the last input event.
There is no foreground process.
The foreground process is being debugged.
The foreground is not locked (see LockSetForegroundWindow).
The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
No menus are active.

解决方案

public static void ActivateWindow(IntPtr mainWindowHandle)
{
    //check if already has focus
    if (mainWindowHandle == GetForegroundWindow())  return;

    //check if window is minimized
    if (IsIconic(mainWindowHandle))
    {
        ShowWindow(mainWindowHandle, Restore);
    }

    // Simulate a key press
    keybd_event((byte)ALT, 0x45, EXTENDEDKEY | 0, 0);

    //SetForegroundWindow(mainWindowHandle);

    // Simulate a key release
    keybd_event((byte)ALT, 0x45, EXTENDEDKEY | KEYUP, 0);

    SetForegroundWindow(mainWindowHandle);
}
private const int ALT = 0xA4;
private const int EXTENDEDKEY = 0x1;
private const int KEYUP = 0x2;
private const uint Restore = 9;

[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsIconic(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr hWnd, uint Msg);

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

参考资料

Win32 ::SetForegroundWindow() not working all the time
SetForegroundWindow only working while visual studio is open