I wrote this for a very simple requirement. I wanted the main window of the application to appear at the same position across invocations. Well, what better a place than the Registry to store these positions?
The class for this purpose, called WindowPosition, is a simple class with a handful of public methods.
WindowPosition(HKEY hKey,TCHAR* szSubKey);
BOOL ValidatePositions(DWORD& dwxPos,DWORD&dwyPos,DWORD&
BOOL GetWindowPositions(DWORD& dwxPos,DWORD& dwyPos,DWORD&
void OnWindowPosChanged(WINDOWPOS* lpwndpos);
Here’s an explanation of the classes used in the preceding code:
- GetWindowPositions. Used to get the window positions stored in the Registry.
- OnWindowPosChanged. Used to set the window positions into the WindowPosition class’ member variables.
- SaveWindowPositions. Used to save the WindowPosition class’s data to the Registry.
When constructing the object, one would have to specify the root key and the subkey to store.
A typical usage of this class can be something like this, and this is how I have implemented it in the sample project that is included with this article.
- In the main window class, one would add a member variable of class WindowPosition, say m_wndPos:
class CWndPosDlg : public CDialog
// Generated message map functions
- One would then intercept the WM_WINDOWPOSCHANGED message for the main window and in the handler and simply pass the WINDOWPOS* data to m_wndPos by calling the m_wndPos.OnWindowPosChanged(…) method.
void CWndPosDlg::OnWindowPosChanged( WINDOWPOS* lpwndpos )
- One could then save the same to the Registry by calling m_wndPos.SaveWindowPositions() right at that moment (as is done above), or defer it to some other time. For example, one could save the window positions on application exit only.
- The next time the application is invoked, we would want the saved window positions to be reflected. You could do this by reading m_wndPos.GetWindowPositions in OnInitDialog (or the equivalent) of the main window and calling SetWindowPos with the retrieved data.
// Set the icon for this dialog. The framework does this
// automatically when the application’s main window is not a
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
if(TRUE == m_wndPos.GetWindowPositions(dwXPos,dwYPos,
SWP_NOOWNERZORDER | SWP_NOZORDER|SWP_NOSIZE);
return TRUE; // return TRUE unless you set the focus
// to a control
Yes, there are a few caveats with this. Nothing so serious, but yes, I would like to fix it and clean it up once I find an elegant way to deal with the issues. If one changes the display resolution, things can get messy!! The main window may even disappear from the visible area of the screen. This is pretty serious and can be annoying.
I would be glad to receive any ideas or suggestions in this matter, or anything for making this a handy class.