我正在寻找一种方法,以防止鼠标移动,如果我的一些条件发生了。
请注意,我不想在OnMouseMove事件上工作,因为对我来说太晚了。
我需要像Cursor.Clip属性这样的东西。有没有能禁用某些鼠标移动方向的API?一种ApiMouse.DisableMovement(Directio.Up | Direction.Down | Direction.Left | Direction.Right)?
发布于 2012-07-22 10:18:15
在对上一个答案的评论中,您可以参考上一个问题的"Form move inside client desktop area"。接受答案中的代码可防止窗口移出桌面。现在,您希望在用户拖动窗口时将光标“固定”到窗口。因此,如果窗口不能进一步移动,则光标也不应进一步移动。
如果我对您的问题的理解是正确的,那么您应该处理WM_NCLBUTTONDOWN消息来计算鼠标移动的限制。然后,您可以使用Cursor.Clip来应用这些限制。
但是,如果您在WM_NCLBUTTONDOWN邮件中应用剪辑矩形,它将被立即删除。如果您将其应用于WM_MOVING消息,则它将在拖动结束时自动删除。
这也是前述问题的解决方案:如果当用户拖动窗口时,鼠标只能在计算出的矩形中移动,那么窗口本身只能在允许的区域中移动。
public const int WM_MOVING = 0x0216;
public const int WM_NCLBUTTONDOWN = 0x00A1;
public const int HT_CAPTION = 0x0002;
private Rectangle _cursorClip = Rectangle.Empty;
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_NCLBUTTONDOWN:
if (m.WParam.ToInt32() == HT_CAPTION)
{
Point location = Cursor.Position;
Rectangle screenBounds = Screen.PrimaryScreen.Bounds;
Rectangle formBounds = Bounds;
_cursorClip = Rectangle.FromLTRB(location.X + screenBounds.Left - formBounds.Left,
location.Y + screenBounds.Top - formBounds.Top,
location.X + screenBounds.Right - formBounds.Right,
location.Y + screenBounds.Bottom - formBounds.Bottom);
}
break;
case WM_MOVING:
Cursor.Clip = _cursorClip;
break;
}
base.WndProc(ref m);
}发布于 2012-07-22 05:23:26
如果你不喜欢覆盖OnMouseMove,那么你可能会喜欢覆盖WndProc。“捕捉”窗口鼠标移动的消息,并根据您的规则丢弃它们。这是我知道的最快的方法。
private const int WM_MOUSEMOVE = 0x0200;
private const int MK_LBUTTON = 0x0001;
protected override void WndProc(ref Messsage msg)
{
switch(msg.Msg)
{
case WM_MOUSEMOVE: // If you don't want the cursor to move, prevent the code from reaching the call to base.WndProc
switch (msg.WParam.ToInt32())
{
case MK_LBUTTON: // the left button was clicked
break;
}
break;
}
base.WndProc(ref msg);
}使用LParam和WParam可提供有关鼠标当前状态的更多信息。请查看this以更好地了解。
编辑要获得鼠标的坐标,请检查此question.。它表明:
int x = msg.LParam.ToInt32() & 0x0000FFFF;
int y = (int)((msg.LParam.ToInt32() & 0xFFFF0000) >> 16)
Point pos = new Point(x, y);https://stackoverflow.com/questions/11595839
复制相似问题