Home > MFC, Windows API > How to create a topmost window using SetWindowPos?

How to create a topmost window using SetWindowPos?

A topmost window is one which stays on top of other windows even while it’s not in focus. Normally all application popup windows will go to background once they lose focus but a topmost window doesn’t.

Let me explain or show you the code which does this. Everybody knows how to achieve this but still some don’t, so for them here is how we do this and as always in the form of a function.

void SetTopMost( HWND hWnd, const BOOL TopMost )
   ASSERT( ::IsWindow( hWnd ));
   HWND hWndInsertAfter = ( TopMost ? HWND_TOPMOST : HWND_NOTOPMOST );
   ::SetWindowPos( hWnd, hWndInsertAfter, 0, 0 , 0 , 0, SWP_NOMOVE | SWP_NOSIZE );

The second parameter passed to ::SetWindowPos is the one that does the trick. It’ called hwndInsertAfter, if we specify the after window as HWND_TOPMOST then we get a topmost window, if we specify after window as HWND_NOTOPMOST then topmost setting is unset and our window becomes a normal window.

Equivalent MFC variables for HWND_TOPMOST and HWND_NOTOPMOST are wndTopMost and
wndNoTopMost respectively.

HWND_xxxxx variable are mere #defines just have a look.

#define HWND_TOP        ((HWND)0)
#define HWND_BOTTOM     ((HWND)1)
#define HWND_TOPMOST    ((HWND)-1)
#define HWND_NOTOPMOST  ((HWND)-2)

::SetWindowPos is an interesting function, we can use it

  1. To change the tab order/z-order of a control
  2. To ‘just’ move a control (SWP_MOVE)
  3. To ‘just’ size a control (SWP_SIZE)
  4. To generate ‘just’ nc-paint messages
  5. To generate ‘just’ nc-calcsize messages
  6. To repaint a window

As a homework suggest you to have a look at the flags that are passed to it.

  1. john
    June 14, 2009 at 11:14 pm

    plz let me know the code logic/ apis to identify, which window user is workg..i.e the topmost z order window..i tried getactiv window, getforegrnd window apis, but tis not workg.

  2. December 2, 2008 at 1:30 pm

    Totally agreed with blog

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: