仅在指定区域限制鼠标移动 [英] Restrict Mouse Move only on a Specified Area

查看:32
本文介绍了仅在指定区域限制鼠标移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void MoveCursor(){//设置当前光标,移动光标的位置,//并将其剪切矩形设置为表单.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);}

我正在使用上面的代码来限制移动,但我仍然能够将鼠标移到表单之外?

我可以将鼠标移动限制在表单中的指定区域吗?请指教...

解决方案

更新答案:

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

BOOL WINAPI ClipCursor(RECT *lpRect);

看看这个链接对于 Win32 API 代码,这个来自 C# 的 pinvoke.>

有一对名为 SetCapture/ReleaseCapture 将鼠标限制在某个窗口范围内.

您需要使用 PInvoke 来使用它们,但这会起作用.

[DllImport("user32.dll")]静态外部 IntPtr SetCapture(long hWnd);SetCapture(Control.Handle);

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

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);
}

I am using the above code to Restrict the movement but still I am able to move the mouse outside the form?

Can I restrict the mouse movement to a specified area in the form? Please advise...

解决方案

Updated answer:

ClipCursor is the API function you require. You will need to supply screen-based coordinates.

BOOL WINAPI ClipCursor(RECT *lpRect);

take a look at this link for the Win32 API code, and this one for pinvoke from C#.

There is pair of Win32 API functions called SetCapture/ReleaseCapture that will restrict the mouse to a certain window bounds.

You will need to use PInvoke to use them, but this will work.

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

SetCapture(Control.Handle);

One thing to bear in mind, is that if used incorrectly, it's possible that the user will not be able to click the [X] to shut down your application because the mouse will not be able to get to the title bar.

这篇关于仅在指定区域限制鼠标移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆