📅  最后修改于: 2023-12-03 15:38:53.823000             🧑  作者: Mango
在编写 C# 应用程序时,有时需要获取鼠标的位置。本文将介绍如何使用 C# 获取鼠标的位置。
获取鼠标的位置有多种方式,在此介绍其中两种方法:
System.Windows.Forms.Cursor
类获取鼠标位置最常用的方法是使用 System.Windows.Forms.Cursor
类。该类提供了静态属性 Position
,返回鼠标当前的屏幕坐标。
// 获取鼠标位置
Point point = Cursor.Position;
// 输出坐标
Console.WriteLine("鼠标当前位置坐标为:(" + point.X + ", " + point.Y + ")");
GetCursorPos
函数除了使用 System.Windows.Forms.Cursor
类,还可以使用 Windows API 函数 GetCursorPos
获取鼠标位置。该函数需要一个 POINT
结构体来接收鼠标的坐标值。
// 导入 GetCursorPos 函数
[DllImport("user32.dll")]
static extern bool GetCursorPos(out POINT lpPoint);
// POINT 结构体,用于接收鼠标坐标
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
}
// 获取鼠标位置
POINT point;
GetCursorPos(out point);
// 输出坐标
Console.WriteLine("鼠标当前位置坐标为:(" + point.X + ", " + point.Y + ")");
以上介绍了两种获取鼠标位置的方法,其中第一种方法使用 System.Windows.Forms.Cursor
类,第二种方法使用了 Windows API 函数 GetCursorPos
。选择哪种方法取决于具体情况,如果需要频繁地获取鼠标位置,推荐使用第二种方法。