重新注册用户定义的窗口类 - C++

Jim*_*ell 5 c++ winapi

我从RegisterClassEx下面的代码调用中得到一个类已经存在错误.此代码位于类构造函数中:

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);
}
Run Code Online (Sandbox Code Playgroud)

这个代码第一次执行时,它没有任何问题.当调用类析构函数时,它会取消注册该类:

::UnregisterClass( s_pwcWindowClass, this->m_hInstance );
Run Code Online (Sandbox Code Playgroud)

这一切都很好,第一次通过.对构造函数的后续调用导致RegisterClassEx失败ERROR_CLASS_ALREADY_EXISTS.我究竟做错了什么?

c-s*_*ile 8

UnregisterClass()如果系统中有该类的窗口,则会失败(不会删除该类).因此,您需要::DestroyWindow()为使用该类创建的所有窗口.


Kit*_*tet 5

无论如何,当以后需要时,我不会取消注册课程。我会像这样测试 ERROR_CLASS_ALREADY_EXISTS :

ATOM reg=RegisterClassEx(&m_wcx);
DWORD err=GetLastError();
if(!reg && !(err==ERROR_CLASS_ALREADY_EXISTS)){
    //throw only if not successful and not already registered
}
Run Code Online (Sandbox Code Playgroud)