Issue with SetForegroundWindow in .NET

后端 未结 4 814
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 07:17

I\'m using SetForegroundWindow API in .NET using PInvoke.

When I use the API while debugging in Visual Studio its works perfectly. But it doesn\'t work always when

4条回答
  •  温柔的废话
    2021-01-02 07:31

    The trick is to 'fool' windows (not trying to talk in pleonasms) and attach the input to the new thread to which the window-to-focus belongs, I took most of this from the pinvoke website but added a test to restore minimized windows:

    private const uint WS_MINIMIZE = 0x20000000;
    
    private const uint SW_SHOW     = 0x05;
    private const uint SW_MINIMIZE = 0x06;
    private const uint SW_RESTORE  = 0x09;
    
    public static void FocusWindow(IntPtr focusOnWindowHandle)
    {
        int style = GetWindowLong(focusOnWindowHandle, GWL_STYLE);
    
        // Minimize and restore to be able to make it active.
        if ((style & WS_MINIMIZE) == WS_MINIMIZE)
        {
            ShowWindow(focusOnWindowHandle, SW_RESTORE);
        }
    
        uint currentlyFocusedWindowProcessId = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
        uint appThread = GetCurrentThreadId();
    
        if (currentlyFocusedWindowProcessId != appThread)
        {
            AttachThreadInput(currentlyFocusedWindowProcessId, appThread, true);
            BringWindowToTop(focusOnWindowHandle);
            ShowWindow(focusOnWindowHandle, SW_SHOW);
            AttachThreadInput(currentlyFocusedWindowProcessId, appThread, false);
        }
    
        else
        {
            BringWindowToTop(focusOnWindowHandle);
            ShowWindow(focusOnWindowHandle, SW_SHOW);
        }
    }
    

提交回复
热议问题