这是第一次调用Sleep_Detection(),它是一个包含RegisterClass()的函数:
//some codes here...
Execute_Command(0);
Sleep_Detection(); **//First time calling, no problem**
这是第二次调用Sleep_Detection(),但它现在从SleepDetectionProc()回调函数内部调用,此处发生错误。 我使用了GetLastError(),在这里我得到了错误代码1410,这意味着" ERROR_CLASS_ALREADY_EXISTS"。
LRESULT _stdcall SleepDetectionProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_POWERBROADCAST)
{
if (wParam == PBT_APMRESUMESUSPEND)
{
cout << "System restored" << endl;
Execute_Command(0);
Sleep_Detection(); **//Second time calling, error code 1410**
}
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
这是Sleep_Detection()函数:
void Sleep_Detection(void)
{
WNDCLASS WindowClass = { 0 };
WindowClass.lpfnWndProc = SleepDetectionProc;
WindowClass.lpszClassName = (L"Sleep detection");
if (!GetClassInfo(WindowClass.hInstance, WindowClass.lpszClassName, &WindowClass))
{
if (!RegisterClass(&WindowClass))
{
cout << "Cannot register class (Error Code: " << GetLastError() << ")" << endl;
exit(EXIT_FAILURE);
}
else
cout << "registered" << endl;
}
else
cout << "Class already exists" << endl;
HWND WinHandle = NULL;
if (!FindWindow(WindowClass.lpszClassName, ConsoleTitle))
{
if ((WinHandle = CreateWindow(L"Sleep detection", L"", 0, 0, 0, 0, 0, NULL, NULL, NULL, 0)) == NULL)
{
cout << "Cannot create window (Error Code: " << GetLastError() << ")" << endl;
exit(EXIT_FAILURE);
}
else
cout << "window created" << endl;
}
else
cout << "Window already exists" << endl;
int upRes;
MSG Message;
while (upRes = GetMessage(&Message, WinHandle, 0, 0))
{
if (upRes == -1)
{
cout << "An error occurred when getting window messages (Error Code: " << GetLastError() << endl;
exit(EXIT_FAILURE);
}
else
{
cout << "Got Message!" << endl;
TranslateMessage(&Message);
DispatchMessage(&Message);
}
}
}
所以我基本上调用了Sleep_Detection()两次,它也调用了RegisterClass()函数。我猜错误可能与覆盖RegisterClass()?
有关答案 0 :(得分:3)
WNDCLASS WindowClass = { 0 }; WindowClass.lpfnWndProc = SleepDetectionProc; WindowClass.lpszClassName = (L"Sleep detection");
WindowClass.hInstance
为零,即使窗口类已经存在,也会导致GetClassInfo()
失败,因为参数NULL
的{{1}}值是为类保留的由系统定义,在MSDN page:
的hInstance
创建该类的应用程序实例的句柄。至 检索有关系统定义的类的信息(例如 按钮或列表框),将此参数设置为 NULL 。
因此总会尝试hInstance
,这当然在第二次尝试时失败了。
要更正错误,请按以下方式初始化RegisterClass
:
WindowClass.hInstance
如果从DLL调用代码,请将WindowClass.hInstance = GetModuleHandle(NULL); // get hInstance of current process
替换为该DLL的句柄。顺便说一句,HMODULE
is interchangeable with HINSTANCE
,这是模块的基地址。