很簡單,就是在WinProc函數里增加一個WM_ACTIVATE消息處理,然后調用ClipCursor來限制鼠標的可移動范圍.
好像WIN32沒有直接將RECT從client坐標轉換成screen坐標的,所以我自己寫了這么個函數.
當然這里給出的代碼并不是高效的,GetSystemMetrics不應該在WinProc里調用,但這里只是給出了一種解決方案,暫不考慮代碼執行效率的問題.
//-------------------------------------------------------------------------
// Translates rect from client coordinate to screen coordinate.
//-------------------------------------------------------------------------
void RectFromClientToScreen(LPRECT rect)
{
????POINT tmp;
?
????tmp.x = rect->left;
????tmp.y = rect->top;
????ClientToScreen(g_mainWindowHandle, &tmp);
????rect->left = tmp.x;
????rect->top? = tmp.y;
????tmp.x = rect->right;
????tmp.y = rect->bottom;
????ClientToScreen(g_mainWindowHandle, &tmp);
????rect->right? = tmp.x;
????rect->bottom = tmp.y;
}
//-------------------------------------------------------------------------
// Main windows event procedure.
//-------------------------------------------------------------------------
LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
??? PAINTSTRUCT ps;???? // used in WM_APINT
??? HDC hdc;??????????? // handle to a device context
????int screenWidth? = GetSystemMetrics(SM_CXSCREEN);
????int screenHeight = GetSystemMetrics(SM_CYSCREEN);
?
????RECT screenRect = {0, 0, screenWidth, screenHeight};
????RECT clientRect;?
?
????// what is the message
????switch (msg)
????{
????case WM_CREATE:
????????// do initialization stuff here
????????return 0;
????case WM_PAINT:
????????// start painting
????????hdc = BeginPaint(hwnd, &ps);
????????// end painting
????????EndPaint(hwnd, &ps);
????????return 0;
????case WM_ACTIVATE:
???????if(LOWORD(wParam) == WA_ACTIVE)
???????{
??????????GetClientRect(g_mainWindowHandle, &clientRect);???
??????????RectFromClientToScreen(&clientRect);???
??????????ClipCursor(&clientRect);
???????}
??? else if(LOWORD(wParam) == WA_INACTIVE)
?????? ClipCursor(&screenRect);
???????break;
????case WM_DESTROY:
??????? // kill the application
??????? PostQuitMessage(0);
??????? return 0;
??? }
??? // process any messages that we did not take care of
??? return DefWindowProc(hwnd, msg, wParam, lParam);
}