Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-registering User-defined Window Class - C++

Tags:

c++

winapi

I'm getting a class already exists error from the call to RegisterClassEx in the following code. This code is in a class constructor:

this->m_wcx.cbSize = sizeof(WNDCLASSEX);  // size of structure
this->m_wcx.style = CS_HREDRAW | CS_VREDRAW; // initially minimized
this->m_wcx.lpfnWndProc = &WndProc;       // points to window procedure
this->m_wcx.cbClsExtra = 0;               // no extra class memory
this->m_wcx.cbWndExtra = 0;               // no extra window memory
this->m_wcx.hInstance = m_hInstance;      // handle to instance
this->m_wcx.hIcon = ::LoadIcon( NULL, IDI_APPLICATION ); // default app icon
this->m_wcx.hCursor = ::LoadCursor( NULL, IDC_ARROW ); // standard arrow cursor
this->m_wcx.hbrBackground = NULL;         // no background to paint
this->m_wcx.lpszMenuName = NULL;          // no menu resource
this->m_wcx.lpszClassName = s_pwcWindowClass; // name of window class
this->m_wcx.hIconSm = NULL;               // search system resources for sm icon

// Register window class.
if ( (this->m_atom = ::RegisterClassEx( &m_wcx )) == 0 )
{
    dwError = ::GetLastError();
    TRACE(_T("Failed to register window class.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), dwError, _T(__FILE__), __LINE__);
    THROW(dwError);
}

This first time this code executes, it works without any problems. When the class destructor is called it unregisters the class:

::UnregisterClass( s_pwcWindowClass, this->m_hInstance );

This all works fine the first time through. Subsequent calls to the constructor result in RegisterClassEx failing with ERROR_CLASS_ALREADY_EXISTS. What am I doing wrong?

like image 731
Jim Fell Avatar asked Apr 26 '11 14:04

Jim Fell


2 Answers

UnregisterClass() will fail (will not delete the class) if there are windows of that class in the system. So you will need to ::DestroyWindow() for all windows that were created with the class.

like image 139
c-smile Avatar answered Oct 19 '22 13:10

c-smile


I wouldn't unregister a class when it is needed later on anyway. I'd test for ERROR_CLASS_ALREADY_EXISTS like so:

ATOM reg=RegisterClassEx(&m_wcx);
DWORD err=GetLastError();
if(!reg && !(err==ERROR_CLASS_ALREADY_EXISTS)){
    //throw only if not successful and not already registered
}
like image 32
Kitet Avatar answered Oct 19 '22 13:10

Kitet