Creating a Win32 Window Wrapper Class
by Oluseyi Sonaiya
Anyone familiar with the Win32 API knows that the process for creating windows is rather lengthy: you create a WNDCLASSEX structure, initialize its members and register it (per window class); create the window, check for the validity of the returned handle, and finally display the window. Of course, I neglected to mention that initializing the WNDCLASSEX structures members requires that you define a window procedure first…
So it's logical that the enterprising C++ developer would like to wrap all of the above in a nice class that would allow her write something like:
Window *wnd = new Window(…);
wnd->Create(…);
wnd->Show(…);
// use window
// window's destructor is automatically called, and
// performs necessary cleanup
Doesn't look to hard… Ha! it took me a good 2 hours to perfect the object association and proper message pump termination. I'll share my design principles, implementation, revisions and discoveries in the process of creating this wrapper class. I will not be covering the fundamentals of creating windows with Win32, or any other technology I consider to be elementary. There are several good references available on the web for these topics; please take advantage of them.
Without further ado, let's dive in!
Design Principles
In writing a Win32 window wrapper class, I wanted a method that would allow for as little coupling into the main application as possible, that would require the minimum user intervention necessary yet be extremely flexible. I also wanted the user to be able to extend the class without having to inherit or reimplement any methods. Most methods of wrapping windows in Win32 that I have seen on the web require the user to implement a full window procedure and handle all messages she is interested in (you may notice my habitual use of the singular feminine pronoun; deal with it). Microsoft's MFC and Borland's VCL use preprocessor "message maps", restricting the flexibility of the window class in terms of dynamic runtime modification since they are evaluated at compile time. Given the advent of the Standard Template Library and its integral part in the C++ language, I was sure I could find a container that would be as fast and flexible as the image in my mind.
As much as possible, I wanted defaults such that the wrappers could be used with minimal code. I also wanted the class to be sufficiently generic that it could be used for general-purpose applications as well as for high-performance applications like videogames. Over the course of the class development various features to accomplish this were added, and it was constantly interesting to find a way to integrate such features in a consistent way. Wherever possible and reasonable, I also tried to use names consistent with the Win32 API as a form of assitance to the developer.
The Window Class
Windows in Win32 are represented by window handles , so the logical first object to encapsulate is the window handle. Anybody who has tried to wrap window classes knows that you can not initialize the window class with a class method as the window procedure unless it is a static method, so the class also needs a static "message router" that determines which instance of the class is the recipient of the message and calls that instance's window procedure. So how exactly do we determine which instance should receive the message?
Every window has a 32-bit value associated with it intended for use by the application. This value can be set via the SetWindowLong function and retrieved with the GetWindowLong , and this is the core of the message routing technique.
LRESULT CALLBACK Window::MsgRouter(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
Window *wnd = 0;
// retrieve associated Window instance
wnd = reinterpret_cast<Window *>(::GetWindowLong(hwnd, GWL_USERDATA));
// call the windows message handler
wnd->WndProc(message, wparam, lparam);
}
While this looks perfect, where and when was this value stored? At first I stored it during my Window::Create routine, but I ran into problems. You see, some messages are sent before CreateWindowEx returns – WM_NCCREATE, WM_NCCALCSIZE and WM_CREATE (in that order). If the value does not exist by the time WM_NCCREATE is called then, by some mysterious Windows behavior that I still don't understand, the value never gets inserted. The solution? The WM_NCCREATE message must be handled explicitly within the message router, with the object pointer being stored at this point instead. Okay, but where do we get the value from? The CreateWindowEx function allows the passing of a (void) pointer to window creation data. This data is made available to the window procedure as the lparam parameter in the form of an LPCREATESTRUCT. As an added precaution, we go ahead and store the window handle at this point.
LRESULT CALLBACK Window::MsgRouter(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
Window *wnd = 0;
if (message == WM_NCCREATE) {
// retrieve Window instance from window creation data and associate
wnd = reinterpret_cast<Window *>((LPCREATESTRUCT)lparam)->lpCreateParams;
::SetWindowLong(hwnd, GWL_USERDATA, reinterpret_cast<long>(wnd));
// save window handle
wnd->SetHWND(hwnd);
} else
// retrieve associated Window instance
wnd = reinterpret_cast<Window *>(::GetWindowLong(hwnd, GWL_USERDATA));
// call the windows message handler
wnd->WndProc(message, wparam, lparam);
}
Message Handling
Alright! We've got our object properly associated with the window handle, and messages being properly routed. But what about that flexibility we mentioned earlier? As it stands, the window procedure has to handle all possible messages – an approach that would require reengineering the class for every new application. Not going to cut it.
In considering how to make this more flexible, I was struct by the fact that MFC and VCL call their methods of associating window messages with message handlers message maps. Being the STL afficionado that I am, that immediately struct a chord with me. How's about I use a std::map to tie a particular message to a particular message handler? That way I could insert and replace a message handler at any time without modifying the class.
For those of you not familar with the Standard Template Library (STL), I heartily recommend SGI's STL Documentation as both an introduction and a reference.
typedef long (* tyMessageHandler)(Window &, HWND, long, long);
typedef std::map<long, tyMessageHandler> tyMessageMap;
typedef tyMessageMap::iterator tyMessageIterator;
The Window class contains a single instance of tyMessageMap . This message map is then searched for the existence of a handler for a given message by the message router, and if none exist the default window procedure is invoked. I also chose to provide two (static) message handlers, partly as a template and partly to provide default functionality.