tags:

views:

1336

answers:

6

I have a piece of code that brings the window under the cursor to the foreground using the SetForegroundWindow API for WinXP. I have been testing it for Vista but the API seems to no longer do the job correctly.

AllowSetForeground did not help, my process is a background process.

What can I use to accomplish this?

+2  A: 

Try the following code and see if it works for you:

SetWindowPos(WndHandle,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE OR SWP_NOSIZE);
SetWindowPos(WndHandle,HWND_NOTOPMOST,0,0,0,0,SWP_SHOWWINDOW OR SWP_NOMOVE OR SWP_NOSIZE);
jn_
+1  A: 

If SetForegroundWindow() fails, have you tried setting the window WS_EX_TOPMOST and then immediatly non top most right after calling SetForegroundWindow()?

It might have something to do with people rightfully complaining about applications poping all over the place when you least expect it.

Coincoin
+1  A: 
VOID SwitchToThisWindow(HWND hWnd, BOOL fAltTab);

Works on XP to Windows 7 http://msdn.microsoft.com/en-us/library/ms633553.aspx

Duncan Smart
A: 

It's a Win32 FAQ for 18 years !

See Google Groups for the official method.

link or excerpt please!
Eric Grange
+3  A: 

Just a warning: there was a public API to do that (SetForegroundWindow), now it does not bring the window in the foreground anymore.

Now the window just flashes.

But this was for a reason. Applications doing that "steal" the focus from the current window (often without a good reason) and can lead to all kind of problems.

So before trying to circumvent the protections put by the OS against this kind of behavior, make sure you will not annoy your users. Ask yourself: "do I really-really have to jump in my user's face, even if my application is in the background?"

Mihai Nita
No offense, but personally I dislike answers like this. He wasn't asking for advice on how to design his program, he wanted an answer to a specific technical problem.
korona
Well, I'm going to stick up for this answer! One of the most helpful things an answer can do is to show the original questioner that perhaps the question they're asking indicates they're doing the wrong thing.
DavidK
Agreed. The answer isn't off topic and is relevant :)
Thomas Bratt
A: 

If using MFC, this worked for me in Windows 7 x64:

    RECT rc;
    m_pMainWnd->GetWindowRect(&rc);

    int nBoxWidth = rc.left-rc.right;
    int nBoxHeight = rc.bottom-rc.top;
    int nBoxTop = rc.top;
    int nBoxLeft = rc.left;

    SetWindowPos(m_pMainWnd->GetSafeHwnd(), HWND_TOPMOST,
                    nBoxLeft, nBoxTop, nBoxWidth, nBoxHeight,
                    SWP_NOMOVE || SWP_NOSIZE);
    SetWindowPos(m_pMainWnd->GetSafeHwnd(), HWND_NOTOPMOST,
                    nBoxLeft, nBoxTop, nBoxWidth, nBoxHeight,
                    SWP_SHOWWINDOW || SWP_NOMOVE || SWP_NOSIZE);
JCF