I'm writing a very simple program to clip the mouse to a specified window. It runs from the system tray without a visible window. Because there will be multiple instances of the same window, it uses EnumWindows()
to iterate through every top-level window and compare their hwnd with GetForegroundWindow()
. When true, it runs the standard ClipCursor()
code. ClipCursor()
returns TRUE
, and, I've asserted that the RECT
set by GetClipCursor()
is the exact same as the RECT
passed to ClipCursor()
. Yet, the cursor is free to move anywhere on the screen.
I've checked that the values in the RECT
are the exact values of the window, I've compiled the program in release mode and ran it with admin rights, still nothing. The code below is exactly what runs after we've found the HWND
of the GetForegroundWindow()
:
// Get the window client area.
GetClientRect(hwnd, &rc);
// Convert the client area to screen coordinates.
POINT pt = { rc.left, rc.top };
POINT pt2 = { rc.right, rc.bottom };
ClientToScreen(hwnd, &pt);
ClientToScreen(hwnd, &pt2);
SetRect(&rc, pt.x, pt.y, pt2.x, pt2.y);
clipped = true;
ClipCursor(&rc);
RECT rect;
GetClipCursor(&rect);
assert(rect.bottom == rc.bottom);
assert(rect.left == rc.left);
assert(rect.right == rc.right);
assert(rect.top == rc.top);
I've removed a lot of the checks because they were getting annoying (I was using MessageBox()
's), but this code is certainly running when it's supposed to. The cursor just isn't getting clipped, and I can't fathom why.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…