14

Pre-Text/ Question

I am trying to make a fairly simple tool to help debug variable values. For it to be completely self contained within the class is what I am aiming for. The end product I can use a function in the class like ShowThisValue(whatever).

The problem I am having is that I can't figure out, if possible, to have the procedure within the class. Here is the short version, with the problem.

-Code updated again 11/29/13- -I have put this in its own project now.

[main.cpp]

viewvars TEST; // global
TEST.CreateTestWindow(hThisInstance); // in WinMain() right before ShowWindow(hwnd, nFunsterStil);

[viewvars.h] The entire updated

class viewvars {

private:
    HWND hWindow;            // the window, a pointer to
    LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);        
    static LRESULT CALLBACK ThisWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);

public:        
    viewvars(); // blank constructor
    int CreateTestWindow(HINSTANCE hInst);

};

// blank constructor
viewvars::viewvars() {}



// create the window
int viewvars::CreateTestWindow(HINSTANCE hInst) {

// variables
char thisClassName[] = "viewVars";     
MSG msg;       
WNDCLASS wincl;  


// check for class info and modify the info
if (!GetClassInfo(hInst, thisClassName, &wincl)) {
    wincl.style = 0;
    wincl.hInstance = hInst;
    wincl.lpszClassName = thisClassName;
    wincl.lpfnWndProc = &ThisWindowProc;
    wincl.cbClsExtra = 0;
    wincl.cbWndExtra = 0;
    wincl.hIcon = NULL;
    wincl.hCursor = NULL;
    wincl.hbrBackground = (HBRUSH)COLOR_BTNSHADOW;
    wincl.lpszMenuName = NULL;

    if (RegisterClass(&wincl) == 0) {
        MessageBox(NULL,"The window class failed to register.","Error",0); 
        return -1;
    }
}  

// create window
hWindow = CreateWindow(thisClassName, "Test", WS_POPUP | WS_CLIPCHILDREN, 10, 10, 200, 200, NULL, NULL, hInst, this);
if (hWindow == NULL) { 
    MessageBox(NULL,"Problem creating the window.","Error",0); 
    return -1; 
} 

// show window
ShowWindow(hWindow, TRUE);

// message loop
while (GetMessage(&msg, hWindow, 0, 0))
{
    TranslateMessage(&msg);  
    DispatchMessage(&msg); 
}    

// then quit window?
DestroyWindow(hWindow);
hWindow = NULL;

return msg.wParam;
}   


// window proc
LRESULT CALLBACK viewvars::ThisWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {

MessageBox(NULL,"Has it gone this far?","Bench",0); 

// variable
viewvars *view;

// ????
if (message == WM_NCCREATE) {
    CREATESTRUCT *cs = (CREATESTRUCT*)lParam; 
    view = (viewvars*) cs->lpCreateParams;

    SetLastError(0);
    if (SetWindowLongPtr(hwnd, GWL_USERDATA, (LONG_PTR) view) == 0) {
        if (GetLastError() != 0) {
            MessageBox(NULL,"There has been an error near here.","Error",0); 
            return FALSE;
        }
    }
}
else {
    view = (viewvars*) GetWindowLongPtr(hwnd, GWL_USERDATA);
}


if (view) return view->WindowProc(message, wParam, lParam);

MessageBox(NULL,"If shown, the above statement did not return, and the statement below did.","Error",0); 

return DefWindowProc(hwnd, message, wParam, lParam);
}


LRESULT viewvars::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) {
// you can access non-static members in here...
MessageBox(NULL,"Made it to window proc.","Error",0);

switch (message)
{
    case WM_PAINT: 
        return 0;
    break;
    case WM_DESTROY:
        PostQuitMessage(0);       
        return 0;
    break;
    default:
        MessageBox(NULL,"DefWindowProc Returned.","Error",0);
        return DefWindowProc(hWindow, message, wParam, lParam);
    break;
}
}

The message boxes appear in this order:

  • Has it made it this far?
  • Made it to window proc
  • DefWindowProc returned
  • Has it made it this far? // repeated?
  • Made it to window proc
  • DefWindowProc returned
  • Problem Creating the Window

Thanks for the help so far. Do you know where the problem might be?enter image description here

5
  • make the windowproc method static.
    – thang
    Nov 28, 2013 at 2:12
  • 2
    It's possible using dynamic thunking technique: stackoverflow.com/a/18326813/1768303
    – noseratio
    Nov 28, 2013 at 2:27
  • 2
    Don't call MessageBox for every message. This creates reentrancy and general confusion. Also, some messages are not expected to yield. Yielding will cause problems. Nov 30, 2013 at 3:12
  • True, I just used those messages to see what it was doing. It didn't work in the first place, so I was just seeing what it was doing. As far as this thing goes, it is the equivalent of debugging each step at a time. I could open the console and cout instead of MessageBox, and get the exact same. Ignore all messages Create Window is not working... Nov 30, 2013 at 16:11
  • You didn't set wincl.cbSize.
    – user253751
    Dec 4, 2013 at 23:06

5 Answers 5

17

To use a non-static class method as a window procedure requires a dynamically-allocated thunk, which is an advanced technique that I will not get into it here.

The alternative is to declare the class method as static, then it will work as a window procedure. Of course, being a static method, it can no longer access non-static class members without an instance pointer. To get that pointer, you can have the class pass its this pointer to the lpParam parameter of CreateWindow/Ex(), then the window procedure can extract that pointer from the WM_NCCREATE message and store it in the window using SetWindowLong/Ptr(GWL_USERDATA). After that, subsequent messages can retrieve that pointer using GetWindowLong/Ptr(GWL_USERDATA) and thus be able to access non-static members of that object. For example:

class viewvars
{
private:
    HWND hWindow;
    LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);

    static LRESULT CALLBACK ThisWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
public:
    int CreateTestWindow(HINSTANCE hInst);
};

int viewvars::CreateTestWindow(HINSTANCE hInst)
{ 
    WNDCLASS wincl;

    if (!GetClassInfo(hInst, thisClassName, &wincl))
    {
        ...
        wincl.hInstance = hInst;
        wincl.lpszClassName = thisClassName;
        wincl.lpfnWndProc = &ThisWindowProc;

        if (RegisterClass(&wincl) == 0)
            return -1;
    }

    hWindow = CreateWindow(..., hInst, this);
    if (hWindow == NULL)
        return -1;

    ...

    MSG msg;
    while (GetMessage(&msg, hWindow, 0, 0))
    {
        TranslateMessage(&msg);  
        DispatchMessage(&msg); 
    }

    DestroyWindow(hWindow);
    hWindow = NULL;

    return msg.wParam;
}

LRESULT CALLBACK viewvars::ThisWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    viewvars *view;

    if (message == WM_NCCREATE)
    {
        CREATESTRUCT *cs = (CREATESTRUCT*) lParam; 
        view = (viewvars*) cs->lpCreateParams;

        SetLastError(0);
        if (SetWindowLongPtr(hwnd, GWL_USERDATA, (LONG_PTR) view) == 0)
        {
            if (GetLastError() != 0)
                return FALSE;
        }
    }
    else
    {
        view = (viewvars*) GetWindowLongPtr(hwnd, GWL_USERDATA);
    }

    if (view)
        return view->WindowProc(message, wParam, lParam);

    return DefWindowProc(hwnd, message, wParam, lParam);
}

LRESULT viewvars::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
    // you can access non-static members in here...

    switch (message)
    {
        case WM_PAINT: 
            return 0;

        case WM_DESTROY:
            PostQuitMessage(0);       
            return 0;

        default:
            return DefWindowProc(hWindow, message, wParam, lParam);
    }
}
11
  • +1 the code i use to frequently do this when using unwrapped (ATL, MFC, WTL, etc..) Windows API windowing code is nearly identical to this method, and frankly I'd up-vote this a dozen more times if I could. It bears mentioning the template is slightly different when using a dialog procedure (a different window-long constant, etc) but the premise is still the same. Nice answer.
    – WhozCraig
    Nov 28, 2013 at 2:50
  • Thanks, I think this will work. Right now I am having a problem, though, it gets hung on the registering class part. My register class paragraph is the same as you posted. Is there anything I need to change or add? I have no previous registration for it. I have a few questions, too. So where it says access member info, does it mean public/ private variables in the class? what about other functions I add? Thanks. Nov 28, 2013 at 5:48
  • Are you filling out all of the WNDCLASS members, not just the few I showed? It is unusual for RegisterClass() to hang. And yes, I am referring to all of the class members (variables, methods, etc), public and private, it does not matter (the static procedure is itself a member, so it has access to all of them). Nov 28, 2013 at 7:39
  • I finished the WNDCLASS members // check for class info and modify the info if (!GetClassInfo(hInst, thisClassName, &wincl)) { wincl.style = CS_DROPSHADOW; wincl.hInstance = hInst; wincl.lpszClassName = thisClassName; wincl.lpfnWndProc = &ThisWindowProc; wincl.cbClsExtra = 0; wincl.cbWndExtra = 0; wincl.hIcon = NULL; wincl.hCursor = NULL; wincl.hbrBackground = (HBRUSH)COLOR_BTNSHADOW; wincl.lpszMenuName = NULL; if (RegisterClass(&wincl) == 0) return -1; } -CONTINUED- Nov 28, 2013 at 16:49
  • CreateWindow() is now giving me trouble. Any ideas? // create window hWindow = CreateWindow(thisClassName, "Test", WS_POPUP | WS_CLIPCHILDREN, 10, 10, 200, 200, NULL, NULL, hInst, this); if (hWindow == NULL) { MessageBox(0,0,0,0); return -1; } Nov 28, 2013 at 16:52
11
+50

The main message loop must not be in your class, and especially not in a "CreateTestWindow" function, as you will not return from that function until your thread receive the WM_QUIT message that makes GetMessage returns 0.

Here is simple implementation of your viewvars class. Key points:

  • The Window Proc is a static member.
  • The link between the Window Proc and the object is made through the use of GWLP_USERDATA. See SetWindowLongPtr.
  • The class DTOR destroys the window if it still exists. The WM_DESTROY message set the HWND member to 0.
  • Adding OnMsgXXX methods to the class is simple: declare/define then and just call them from the WindowProc using the 'this' pointer stored in GWLP_USERDATA.

EDIT:

  • As per Mr Chen suggestion, earlier binding of the HWND to the Object (in WM_NCCREATE) to allow message handler as methods during the Window Creation.

I changed the creation styles, to show the window and to be able to move it.

// VIEWVARS.H
class viewvars {

public:
    static viewvars* CreateTestWindow( HINSTANCE hInstance );
    viewvars() : m_hWnd( 0 ) {}
    ~viewvars();

private:
    static LRESULT CALLBACK WindowProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
    static const char * m_pszClassName;
    HWND m_hWnd;

};

// VIEWVARS.CPP
#include "viewvars.h"

const char * viewvars::m_pszClassName = "viewvars";

viewvars * viewvars::CreateTestWindow( HINSTANCE hInst ) {

    WNDCLASS wincl;
    if (!GetClassInfo(hInst, m_pszClassName, &wincl)) {
        wincl.style = 0;
        wincl.hInstance = hInst;
        wincl.lpszClassName = m_pszClassName;
        wincl.lpfnWndProc = WindowProc;
        wincl.cbClsExtra = 0;
        wincl.cbWndExtra = 0;
        wincl.hIcon = NULL;
        wincl.hCursor = NULL;
        wincl.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1);
        wincl.lpszMenuName = NULL;
        if (RegisterClass(&wincl) == 0) {
            MessageBox(NULL,"The window class failed to register.","Error",0);
            return 0;
        }
    }

    viewvars * pviewvars = new viewvars;
    HWND hWnd = CreateWindow( m_pszClassName, "Test", WS_VISIBLE | WS_OVERLAPPED, 50, 50, 200, 200, NULL, NULL, hInst, pviewvars );
    if ( hWnd == NULL ) {
        delete pviewvars;
        MessageBox(NULL,"Problem creating the window.","Error",0); 
        return 0; 
    }

    return pviewvars;

}

 LRESULT CALLBACK viewvars::WindowProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) {

    switch ( uMsg ) {

        case WM_NCCREATE: {
            CREATESTRUCT * pcs = (CREATESTRUCT*)lParam;
            viewvars * pviewvars = (viewvars*)pcs->lpCreateParams;
            pviewvars->m_hWnd = hwnd;
            SetWindowLongPtr( hwnd, GWLP_USERDATA, (LONG)pcs->lpCreateParams );
            return TRUE;
        }

        case WM_DESTROY: {
            viewvars * pviewvars = (viewvars *)GetWindowLongPtr( hwnd, GWLP_USERDATA );
            if ( pviewvars ) pviewvars->m_hWnd = 0;
            break;
        }

        default:
            return DefWindowProc( hwnd, uMsg, wParam, lParam );

    }

    return 0;

}

viewvars::~viewvars() {
    if ( m_hWnd ) DestroyWindow( m_hWnd );
}

Finally, a "main" sample, but beware that there is here no way to end the process. That should be taken care by regular code (another windows).

// MAIN.CPP
#include <Windows.h>
#include "viewvars.h"

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    viewvars * pviewvars = viewvars::CreateTestWindow( hInstance );
    if ( pviewvars == 0 ) return 0;

    BOOL bRet;
    MSG msg;
    while( (bRet = GetMessage( &msg, 0, 0, 0 )) != 0)
    { 
        if (bRet == -1)
        {
            // handle the error and possibly exit
        }
        else
        {
            TranslateMessage(&msg); 
            DispatchMessage(&msg); 
        }
    }

    delete pviewvars;

    return 0;

}
5
  • Now it makes a bit more sense, that is a working example. Thanks. Dec 3, 2013 at 17:46
  • Thanks to you. Good luck with the remaining work in "viewvars" :-)
    – manuell
    Dec 3, 2013 at 18:11
  • 5
    Note that since you don't set the GWLP_USERDATA until after CreateWindow returns, this means that you do not get the change to customize the behavior of messages send as part of window creation. Maybe this isn't important, but just calling it out because it may bite you later. Dec 3, 2013 at 19:02
  • @RaymondChen Thanks. Indeed. Updated.
    – manuell
    Dec 3, 2013 at 21:02
  • 1
    in WM_NCCREATE message add SetWindowPos(hwnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER); just before return to prevent window background flicker on first window appearance.
    – NickSoft
    Mar 1, 2017 at 13:19
3

Unfortunately using an instance method as a C-style callback function for the WndProc won't work. At least not in any straight-forward way.

The reason it doesn't work like that is that an instance method requires the this pointer to be passed in (to point to an instance) and that won't be correctly set by the code calling the WndProc. The Win32 API was originally designed with C in mind so this is one area where you have to use some work-arounds.

One way to work around this would be to create a static method to serve as the window proc and dispatch messages to your class instances. The class instances would have to be registered (read added to a static collection) so the static method would know to dispatch WndProc messages to the instances. Instances would register themselves with the static dispatcher in the constructor and remove themselves in the destructor.

Of course all the registration and unregistration and dispatching overhead is only necessary if your WndProc handler needs to invoke other instance member functions, or access member variables. Otherwise you can just make it static and you're done.

2
  • You do not need a static collection to hold the class instance pointers. When the class creates its window, it can pass its this pointer to the lpParam parameter of CreateWindow/Ex(), then the window procedure can extract that pointer from the WM_NCCREATE message and store it in the window using SetWindowLong/Ptr(GWL_USERDATA). After that, subsequent messages can retrieve that pointer using GetWindowLong/Ptr(GWL_USERDATA) and call non-static methods on it as needed. Nov 28, 2013 at 2:23
  • @RemyLebeau - good point! It's been a while since I've had to deal with this problem so I was mostly going off of old memories Nov 28, 2013 at 2:53
2

Your window procedure is called during CreateWindow. You pass hWindow to DefWindowProc, but hWindow is only set after CreateWindow returns - so you pass DefWindowProc a garbage window handle.

I don't see a nice way to do it. You could set hWindow inside the window procedure, by changing WindowProc to:

LRESULT WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)

(added the hwnd parameter), changing the call to:

return view->WindowProc(hwnd, message, wParam, lParam);

creating the window like this:

hWindow = NULL;
hWindow = CreateWindow(..., hInst, this);
if (hWindow == NULL)
    return -1;

(the first assignment is to make sure hWindow is initialized; the second one is in case CreateWindow fails after calling the window procedure), and adding this at the start of WindowProc:

if(!this->hWindow)
    this->hWindow = hwnd;
6
  • You're right, that seems to be the problem. I looked thoroughly threw it, and couldn't find anywhere where I could set the hWindow. Any idea of where I could set it? Thanks. Dec 1, 2013 at 5:44
  • 1
    I don't see a nice solution either. Perhaps pass the HWND as the first argument to WindowProc. (this would be redundant once hWindow is initialized).
    – user253751
    Dec 1, 2013 at 9:50
  • I tried it, and it ended up giving me errors because of the static. I am beginning to think that if this can be done, it is barely possible. I also looked at a (10 year old) C wrapper class for Win32, and ended up having endless memory leaks (as users described). The code was semi-similar to what I have. Hmm... Dec 1, 2013 at 14:42
  • 1
    I updated my answer with the code changes needed for my solution.
    – user253751
    Dec 1, 2013 at 23:51
  • Thanks, Ive got/had it semi-working. At first the window would come up but would go into some sort of infinite loop, whole window and close buttons flickered. Anyways, now I am having trouble executing the function. In the main file, nothing passes the CreateWindow()/ ShowWindow() for the main window. hwnd = CreateWindowEx (0, szClassName, "Windows App", WS_OVERLAPPEDWINDOW, ..., HWND_DESKTOP, NULL, hThisInstance, NULL); ShowWindow (hwnd, nFunsterStil); TEST.CreateTestWindow(hThisInstance); The main window displays, never makes it to TEST. Any ideas? thanks. Dec 2, 2013 at 4:47
-1

Step through the code in the debugger. When you get to the line

    MessageBox(NULL,"DefWindowProc Returned.","Error",0);
    return DefWindowProc(hWindow, message, wParam, lParam);

You will see something wrong: hWindow is garbage. You are using an uninitialized variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.