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

前端 未结 4 995
执念已碎
执念已碎 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 18:52

    You can't steal focus. Period.

    See this Old New Thing article:

    https://blogs.msdn.microsoft.com/oldnewthing/20090220-00/?p=19083

    0 讨论(0)
  • 2020-12-20 18:58

    You will find that BringWindowToTop or SetForegroundWindow have requirements that must be met before the window will actually be forced to the front over all other windows (applications). If these aren't met, Windows will only flash the application's icon in the taskbar. This article presents a way around that but as 1800 INFORMATION points out, it is not recommended. I guess you'll just have to accept it.

    0 讨论(0)
  • 2020-12-20 19:00

    doesn't ShowWindow(youwindow,SW_SHOWNORMAL) work? -don

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题