SetForegroundWindow only working while visual studio is open

After searching a few days on the internet I have found one posible simple solution to make SetForegroundWindow to work on windows 7: press Alt key before calling SetForegroundWindow.

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

And the win32api imports

  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();

Leave a Comment