Download demo project - 23 Kb
Download source - 6 Kb
Saving the main window size at application exit and restoring it at startup time is
not difficult, but inconvenient, because SDI,MDI and dialog based applications
have to be handled differently. The class
described in this article reduces this coding task to a single function call.
How to use it
- Add Subclass.h Subclass.cpp and MainWndPlacement.h to your project.
#include "MainWndPlacement.h" in the implementation file of your application class (MDI,SDI)
or dialog class (dialog based application).
- For MDI/SDI applications replace in
InitInstance the call
For dialog based applications add in
OnInitDialog the call
How it works
The magic, that a single function call is sufficient for the save/restore task which has
to be done at program startup and and program exit time, is due to the use of a window hook.
The call to
CMainWndPlacement::InitialShow generates an object which manages it
to get all window messages for the main window. As soon as this object gets the
WM_DESTROY message, it
saves the current window placement using the
WriteProfileString function. Later on,
when the WM_NCDESTROY message arrives, the object deletes itself. Hooking an object into
the message loop of a window is quite tricky, but fortunately, the necessary code
has already materialized in some MFC classes which can be obtained on this site.
(see article CHookWnd v1.02 by
PJ Naughter). For this utility, I used Paul DiLascias classes, which served as starting
point for PJ Naughter's extensions. They are implemented in the files Subclass.h
You can edit the constructor of the class
CMainWndPlacement to change
the section and entry where the main window size is stored. Currently "Settings" is
used as section and "MainWndPos" as entry.
CMainWndPlacement is derived from
CSubclassWnd which provides
HookWindow to hook your object to a given window and the virtual method
WindowProc which is called for every message which arrives at the
hooked window. In
WindowProc you can just listen to all the arriving messages,
you can filter them out or you can even generate your own messages.
CMainWndPlacement itself only listens to the messages
One interesting implementation detail concerns the fact, that the class
has only one public method, namely
InitialShow, even the constructor
CMainWndPlacement is private. Because of that, one can not allocate
CMainWndPlacement object on the stack or make it a member variable of another class.
Generally such a technique restricts the flexibility of a class severely and
should only be used for special cases (like this one).
Just imagine what else can be done with a class like
consider the use of a window hook, when you want to add functionality to existing windows
and when these windows belong to different C++ classes.