SetForegroundWindow only working while visual studio is open

前端 未结 2 906
太阳男子
太阳男子 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:48

    I had an issue with sending the Alt-key as it forced the window menu to open when I selected enter (instead of the OK button which is what I wanted).

    This worked for me:

    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(0, 0, 0, 0);
    
        SetForegroundWindow(mainWindowHandle);
    }
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题