SetForegroundWindow only working while visual studio is open

前端 未结 2 910
太阳男子
太阳男子 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);
    }
    

提交回复
热议问题