How do I force my app to come to the front and take focus?

前端 未结 4 1023
执念已碎
执念已碎 2020-12-20 18:26

I\'m working on an application that happens to be the bootstrap for an installer that I\'m also working on. The application makes a few MSI calls to get information that I n

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 19:09

    Andrew isn't completely correct. Windows does try really hard to stop you from stealing focus, but it is possible using the folowing method.

    1. Attach to the thread of the window that currently has focus.
    2. Bring your window into focus.
    3. Detach from the thread.

    And the code for that would go something like this:

    DWORD dwCurrentThread = GetCurrentThreadId();
    DWORD dwFGThread      = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
    
    
    AttachThreadInput(dwCurrentThread, dwFGThread, TRUE);
    
    // Possible actions you may wan to bring the window into focus.
    SetForegroundWindow(hwnd);
    SetCapture(hwnd);
    SetFocus(hwnd);
    SetActiveWindow(hwnd);
    EnableWindow(hwnd, TRUE);
    
    AttachThreadInput(dwCurrentThread, dwFGThread, FALSE);
    

    You may or may not need to have to run your program with administrative privileges for this to work, but I've used this code personally and it has go the job done.

提交回复
热议问题