Keep a Window on Top

Published on April 12, 2008
This article was written back when Visual Studio 6 was new. As such, I cannot guarantee that the content of this article still applies in modern Windows environments.

This article covers how to force your main program window to stay at the top of the Z-order. Making child views in an MDI application remain on top of other views is a completely different beast, so do not try to use this code for that purpose.

By using the single line of code below, you can force any dialog window to remain on top of all other windows (in the Z-order):

SetWindowPos(&wndTopMost, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);

The first parameter passed to the SetWindowPos() function is a pointer to a window that will precede the current CWnd object in the Z-order. Since I want my window to be top most, a pointer to the value wndTopMost does the trick.

Forcing a frame window for an SDI or MDI application to remain on top uses a similar process, with one slight modification:

CWnd* pMainWnd = AfxGetMainWnd();
pMainWnd->SetWindowPos(&wndTopMost, 0, 0, 0, 0,
                       SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);

Note that we first have to get a pointer to the main window frame, then use that pointer to call the frame window’s SetWindowPos() method.

Restoring Windows to Normal

To restore a dialog window back to a normal state, use the following code:

SetWindowPos(&wndNoTopMost, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);

In this case, a pointer to the value wndNoTopMost is used. Likewise, the following code will work with a frame window:

CWnd* pMainWnd = AfxGetMainWnd();
pMainWnd->SetWindowPos(&wndNoTopMost, 0, 0, 0, 0,
                       SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);

In order to fully understand the other parameters used in this method, you should check out the online documentation for the SetWindowPos() method at the MSDN library.

Comments are closed.

Copyright © 2004-2018 Jonah Bishop. Hosted by DreamHost.