Aug 262008

What’s a TopMost window?

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 move to background once main application window loses focus but a topmost window stays on top, it will not have the input focus though. A good example is our own windows task manager. You can keep it on top to keep an eye on processes that are getting created or for any other purpose for e.g. to keep an eye on process working set.

How to do we setup a TopMost window?

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.

  2 Responses to “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.

  2. Totally agreed with blog

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.