简体   繁体   中英

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

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?

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.

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
}

我有同样的问题,我确信我销毁了使用指定类创建的唯一窗口,然后调用UnregisterClass并返回TRUE(1)但似乎它不会从系统中删除该类,我从中获取ERROR_ALREADY_EXIST接下来调用RegisterClassEx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM