2017-06-15 50 views
2
private void MoveCursor() 
{ 
    // Set the Current cursor, move the cursor's Position, 
    // and set its clipping rectangle to the form. 

    this.Cursor = new Cursor(Cursor.Current.Handle); 
    Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50); 
    Cursor.Clip = new Rectangle(this.Location, this.Size); 
} 

我使用上面的代码来限制运动,但我仍然能够将鼠标移动到窗体之外吗?限制鼠标移动只在指定的区域

我可以限制鼠标移动到表格指定的区域?请指教...

+1

该代码仅在鼠标被控件捕获时才有效。请参阅[MSDN](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.capture(v = vs.110).aspx)。 –

回答

1

更新答案:

ClipCursor是您所需要的API函数。您需要提供基于屏幕的坐标。

BOOL WINAPI ClipCursor(RECT *lpRect); 

看看this link对Win32 API代码,并this one从C#的PInvoke。

有一对称为SetCapture/ReleaseCapture的Win32 API函数会将鼠标限制在某个窗口范围内。

您将需要使用的PInvoke使用它们,但这会工作。

[DllImport("user32.dll")] 
static extern IntPtr SetCapture(long hWnd); 

SetCapture(Control.Handle); 

有一点要记住的是,如果使用不当,它可能是用户将无法点击[X]关闭您的应用程序,因为该鼠标将不能得到标题栏。

+0

[SetCapture](http://www.pinvoke.net/default.aspx/user32.setcapture)和[ReleaseCapture](http://www.pinvoke.net/default.aspx/user32.releasecapture)PInvoke的签名。 –

+0

什么有关[Control.Capture](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.capture(V = vs.110)的.aspx)属性?这似乎并不需要P/Invoke。 –

+0

'Control.Capture'只控制_receives_鼠标输入。如上所述,虽然: >另外,即使前景窗口捕捉到鼠标,用户仍然可以单击另一个窗口,将其带到前台。 – David