以下是一个示例代码,演示如何在WinForm中保持鼠标在边界内:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MouseBoundaryExample
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
// 订阅MouseMove事件
MouseMove += MainForm_MouseMove;
}
private void MainForm_MouseMove(object sender, MouseEventArgs e)
{
// 获取WinForm的客户区域
Rectangle clientArea = ClientRectangle;
// 调整客户区域的大小,使其减去鼠标指针的大小
clientArea.Width -= Cursor.Size.Width;
clientArea.Height -= Cursor.Size.Height;
// 如果鼠标指针超出了客户区域的左侧边界
if (e.X < clientArea.Left)
{
// 将鼠标指针的X坐标设为客户区域的左侧边界
Cursor.Position = new Point(clientArea.Left, Cursor.Position.Y);
}
// 如果鼠标指针超出了客户区域的右侧边界
else if (e.X > clientArea.Right)
{
// 将鼠标指针的X坐标设为客户区域的右侧边界
Cursor.Position = new Point(clientArea.Right, Cursor.Position.Y);
}
// 如果鼠标指针超出了客户区域的上侧边界
if (e.Y < clientArea.Top)
{
// 将鼠标指针的Y坐标设为客户区域的上侧边界
Cursor.Position = new Point(Cursor.Position.X, clientArea.Top);
}
// 如果鼠标指针超出了客户区域的下侧边界
else if (e.Y > clientArea.Bottom)
{
// 将鼠标指针的Y坐标设为客户区域的下侧边界
Cursor.Position = new Point(Cursor.Position.X, clientArea.Bottom);
}
}
}
}
在这个示例中,我们在MainForm_Load
方法中订阅了MouseMove
事件。在MouseMove
事件处理程序MainForm_MouseMove
中,我们首先获取了WinForm的客户区域,然后调整客户区域的大小,以减去鼠标指针的大小。然后,我们检查鼠标指针是否超出客户区域的边界,并相应地调整鼠标指针的位置,使其保持在边界内。
请注意,上述代码仅处理鼠标指针在水平和垂直方向上的移动,如果需要处理其他情况,如鼠标滚轮事件等,请相应地修改代码。
下一篇:保持输出流开启