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.

[sourcecode language=’cpp’]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.

[sourcecode language=’cpp’]#define HWND_TOP        ((HWND)0)
#define HWND_BOTTOM     ((HWND)1)
#define HWND_TOPMOST    ((HWND)-1)
#define HWND_NOTOPMOST  ((HWND)-2)[/sourcecode]

::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.

2 thoughts on “How to create a topmost window using SetWindowPos?

  1. 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.

Appreciate your comments...