我猜应该是类似于把鼠标保持居中在窗口中,但是用户仍然能移动,每次用户移动之后获取鼠标相对于窗口中心移动的数据,再把鼠标重新居中到窗口。
我在 FlappyBird 3D 中实现了这个功能,github 仓库 https://github.com/zouhuidong/FlappyBird3D
主要代码:
/**
* @brief 将鼠标位置设置在窗口中心
* @param hwnd : 窗口句柄
* @return 返回鼠标在窗口中心时的位置
*/
POINT SetCursorAtWindowCenter(HWND hwnd)
{
RECT pos;
POINT cursor;
GetWindowRect(hwnd, &pos);
SetCursorPos(pos.left + (pos.right - pos.left) / 2, pos.top + (pos.bottom - pos.top) / 2);
GetCursorPos(&cursor);
return cursor;
}
/**
* @brief 获取鼠标坐标相对于窗口中心的偏移量
* @param center : 鼠标在窗口中心时的位置
* @return 返回当前鼠标相对于窗口中心的位置
*/
POINT GetCursorMoveCenter(POINT center)
{
POINT p;
GetCursorPos(&p);
p.x -= center.x;
p.y -= center.y;
return p;
}
首先使用 SetCursorAtWindowCenter() 函数设置鼠标居中,然后使用 GetCursorMoveCenter() 函数获取用户的鼠标移动距离。
如果需要持续获取,可以再调用 SetCursorAtWindowCenter() 函数使鼠标居中。
最好能把鼠标隐藏起来,效果更好,但是我试了一些函数,没有成功,所以后来也没有磕这一点,继续往下做了。
还可以设置鼠标不能移动出窗口,见 http://huidong.xyz/?mode=2&id=302