Is it safe to register an existing windows class with a new name?

568 Views Asked by At

I am writing a framework using VC2010, and mixed MFC/Win32. I have a number of control types, which all register their own window classes, and some of them use the WindowProc of one of the standard window class - similar to the following example.

void Button::OnInitClass(WNDCLASS &wndClass)
{       
    Object::OnInitClass(wndClass);
    if(!GetClassInfo(NULL, WC_BUTTON, &wndClass)) {
        throw std::exception("Failed getting window class info.");
    }
    wndClass.lpszClassName = ButtonBase::GetWndClassName();
}

bool Button::Create(CWnd* parent)
{
    if(!WndClassInitialized) {
        static VSCriticalSection cs;
        cs.Enter();
        if(!WndClassInitialized) {
            WNDCLASS wndClass;
            memset(&wndClass, 0, sizeof(WNDCLASS));
            OnInitClass(wndClass);
            assert(wndClass.lpszClassName);
            if(!RegisterClass(&wndClass)) {
                throw std::exception("Error registering window class");
            }
            WndClassInitialized = true;
        }
        cs.Leave();
    }

    DWORD style =   WS_CHILD | WS_CLIPSIBLINGS | BS_PUSHBUTTON | BS_MULTILINE;
    DWORD exStyle = WS_EX_LEFT | WS_EX_LTRREADING;      
    Created = CWnd::CreateEx(exStyle, ButtonBase::GetWndClassName(), "", style , _attribAnchor.Rect, parent, 0) != FALSE;       
    SetFont(_font);
    return Created;
}

It all worked for a long time, but now I am getting a heap corruption now. However, if I use the WC_BUTTON class directly in the CreateEx call I don’t get the heap corruption.

I am in doubt of whether this way of registering a window class where I use the WindowProc from WC_BUTTON is safe. Is it?

If it is safe, then I of cause need to look for the course for the heap corruption elsewhere. But if not, is there a safe way to do what I try to do? (Namely registering an existing class with a new name - which I do in order to be able to recognize the controls from their window class name, given an arbitrary window handle)

I should mention that the heap corruption occurs in a string allocation, and all parameters seem right – so the problem must be somewhere prior to that.

Thanks in advance, Martin

1

There are 1 best solutions below

2
9dan On

I'm afraid mixing MFC/Win32 make it worse. If your main framework/SDK is MFC then why not following MFC's rules and style? Why use ::RegisterClass instead of AfxRegisterClass (a lot simpler). Why register all different classes for mere UI controls?

Usual MFC programs only register new window class for popup or top-level windows (by AfxRegisterClass). MFC CWnd provides basic WndProc for that purpose. If you want a custom design button control you could use window subclassing mechanism.