[ACCEPTED]-How do I force my app to come to the front and take focus?-dialogbasedapp

Accepted answer
Score: 13

Andrew isn't completely correct. Windows 8 does try really hard to stop you from stealing 7 focus, but it is possible using the folowing 6 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 5 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 4 to run your program with administrative 3 privileges for this to work, but I've used 2 this code personally and it has go the job 1 done.

Score: 6

You can't steal focus. Period.

See this Old 1 New Thing article:

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

Score: 0

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

0

Score: 0

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

Score: 0

There ARE good reasons for an app to 'steal' focus. My 8 application is a server loading many driver 7 DLLs. Another application, connecting to 6 the server, has a button that sends a message 5 to the server to show detail information 4 in one of those DLLs (owned by the server, not 3 the client app) for convenience. Unfortunately, this 2 popped open window is usually buried under 1 multiple windows.

More Related questions