[英]How to register WndProc in console app
創建新的Win32應用程序時,我注意到該功能:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
在某個地方調用函數PostMessage或SendMessage時將接收消息,並且我注意到函數WndProc可以接收消息,因為有一個注冊消息的函數:
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SCREENCAPTURE));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_SCREENCAPTURE);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
注意: wcex.lpfnWndProc = WndProc;
我想了解PostMessage()的機制以及如何接收它,因此我創建了一個C ++控制台應用程序以查看是否可以注冊函數WndProc,這是我的嘗試代碼:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int a = 1;//Break point here to see if it's call
return 0;
}
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
return RegisterClassEx(&wcex);
}
void main()
{
MyRegisterClass(GetModuleHandle(NULL));//(HINSTANCE)GetConsoleWindow()
PostMessage(GetConsoleWindow(), 132, 0, 0);
SYSTEMTIME st;
while (true)
{
GetSystemTime(&st);
printf("I'm wanting and waiting and waiting :(, The time is %I64u \n", st.wMilliseconds);
}
}
除非與窗口相關聯,否則窗口過程無法接收消息。 您所要做的就是創建一個窗口類。 您仍然需要為窗口過程(WndProc)創建該類的窗口以接收消息。
根據希望Windows過程接收的消息類型,可以創建一個不顯示在屏幕上的隱藏窗口。 如果您需要處理直接指向控制台窗口的某些消息,例如鍵盤和鼠標事件,則可以改用SetConsoleMode和ReadConsoleInput來獲取這些事件。 還有一個SetConsoleCtrlHandler ,可讓您處理WM_QUERYENDSESSION事件。
Microsoft在MSDN上有一個示例,該示例演示如何使用ReadConsoleInput處理某些控制台輸入事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.