SetForegroundWindow only working while visual studio is open

前端 未结 2 905
太阳男子
太阳男子 2020-12-06 10:22

I\'m trying to set with c# a process window to the foreground / focus (from an application that has no focus in that moment when doing it), therefore I\'m using the user32.d

2条回答
  •  隐瞒了意图╮
    2020-12-06 10:56

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

提交回复
热议问题