Posts Tagged ‘IsIconic’

Move a window to foreground!

May 24, 2008 2 comments

There are times when this feature is quite an annoyance! You are typing in a password and immediately this window pops up in front of you with the focus set on an edit control, so everybody sees your password as you are not aware that another window has come up. A good example would be gmail and MSN. I am typing password into gmail and immediately MSN comes up with the focus set on it’s username edit control. I’ve got trapped few times but now I’m careful.

In spite of it’s side effect this topic is one of the favorite in programming forums. So does SetForegroundWindow work? No it doesn’t but if we use AttachThreadInput along with this API it works.

Are there any other ways to do this? Yes there is! It’s bit tricky but this works in few cases (at least worked with what I tested it on). Works even if I’ve got Mediaplayer/Age of empires running full screen.

So here is function called SetForegroundWindowEx. 🙂

void SetForegroundWindowEx( HWND hWnd )
  if( !IsWindow( hWnd ))

  // Is minimized?
  const BOOL Iconic = ::IsIconic( hWnd );

  // This is bit tricky, we've got to minimize first and then restore
  if( !Iconic )
    ::SendMessage(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0 );

  // Move to top,
  const HWND hWndLastPopup = ::GetLastActivePopup( hWnd );
  ::BringWindowToTop( hWndLastPopup );

  // Now show
  ShowWindow( hWndLastPopup, SW_RESTORE );
}// End SetForegroundWindowEx

But this doesn’t work if we have a modal popup window opened over a window that’s to be moved to foreground.

I’ve used a timer (5000 ms) to test this out. Here is the download link. If this doesn’t work out as expected you can always fallback on to AttachThreadInput. An article by Nishant Sivakumar on this topic given here.

I’ve modified Nishant’s code a bit to fix some bugs, mainly with modal/modeless dialog boxes open but not active when moved to foreground (they were active when moved to background). One bug was with foreground window id not being saved and this was fixed by one of the forum users, so I just copied it here.

// All credit to Nish
void SetForegroundWindowEx( HWND hWnd )
   //Attach foreground window thread to our thread
   const DWORD ForeGroundID = GetWindowThreadProcessId(::GetForegroundWindow(),NULL);
   const DWORD CurrentID   = GetCurrentThreadId();

   AttachThreadInput ( ForeGroundID, CurrentID, TRUE );
   //Do our stuff here
   HWND hLastActivePopupWnd = GetLastActivePopup( hWnd );
   SetForegroundWindow( hLastActivePopupWnd );

   //Detach the attached thread
   AttachThreadInput ( ForeGroundID, CurrentID, FALSE );
}// End SetForegroundWindowEx

This works in all cases so far.

Is a windows applicaton minimized?

%d bloggers like this: