在C#中获取鼠标位置

140

如何获取鼠标位置?我想要获得屏幕坐标系下的位置。

在启动程序时,我想将鼠标位置设置为当前位置。

Location.X = ??
Location.Y = ??

编辑:这必须发生在创建表单之前。


请查看下面的新答案,适用于今天的.NET Framework版本。 - Peter Centellini
10个回答

209

2
Cursor.Position显示我的工具提示偏离屏幕太远:( - Thomas Eyde
28
@Thomas Eyde:我猜,这可能是因为鼠标位置是屏幕坐标,而您的工具提示位置是相对于其父窗口的。您可能需要使用PointToClient - RichieHindle
是的,那就是我必须要做的。 - Thomas Eyde

102

如果您不想引用表单,可以使用Interop获取光标位置:

using System.Runtime.InteropServices;
using System.Windows; // Or use whatever point class you like for the implicit cast operator

/// <summary>
/// Struct representing a point.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
    public int X;
    public int Y;

    public static implicit operator Point(POINT point)
    {
        return new Point(point.X, point.Y);
    }
}

/// <summary>
/// Retrieves the cursor's position, in screen coordinates.
/// </summary>
/// <see>See MSDN documentation for further information.</see>
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);

public static Point GetCursorPosition()
{
    POINT lpPoint;
    GetCursorPos(out lpPoint);
    // NOTE: If you need error handling
    // bool success = GetCursorPos(out lpPoint);
    // if (!success)
        
    return lpPoint;
}

2
如何引用POINT类型? - Manish Dubey
2
添加对System.Drawing的引用 - Bose_geek
1
很棒的解决方案。但是您不需要声明POINT结构体,只需使用Win32Interop.Structs命名空间即可。 - Manpreet Singh Dhillon
@ManpreetSinghDhillon Win32Interop.Structs在.Net Core中是否可用?如果是,它属于哪个NuGet包/系统引用? - Kappacake
使用自己的结构体可以让你将其隐式转换为在代码中使用的任何 Point,这样会更加顺畅。如果 Win32Interop.Structs 对你来说已经足够了,那么请放心使用它! - Mo0gles
@Bose_geek,如果我的表述不够清晰,抱歉。如果你想使用另一个Point结构体,只需更改代码中的那部分,并引用你想要的任何Point结构体/类即可。 - Mo0gles

25

Cursor.Position 可以获取鼠标的当前屏幕位置(如果你在 Control 中,MousePosition 属性也会获得相同的值)。

要设置鼠标位置,你需要使用 Cursor.Position 并给它一个新的 Point 值:

Cursor.Position = new Point(x, y);

在创建窗体之前,您可以在Main方法中完成此操作。


20

针对你提出的具体例子进行回答:

// your example
Location.X = Cursor.Position.X;
Location.Y = Cursor.Position.Y;

// sample code
Console.WriteLine("x: " + Cursor.Position.X + " y: " + Cursor.Position.Y);

不要忘记添加 using System.Windows.Forms;,并将其添加为引用(右键单击引用 > 添加引用 > .NET 选项卡 > Systems.Windows.Forms > 确定)


15

4
不必无礼,这是主要答案的替代方案。我更喜欢这个选项,因为另一个"Cursor.Position"听起来像是文本类型光标(以我之见),而"MousePosition"更加明显。 - James
3
@Jan Dvorak,好的,是的,我认为这可能会有所帮助。我会这样说:“请您提供更多信息,以便我了解这与之前给出的答案有何不同?” - James
@JanDvorak 如果你认为一行代码不能帮助解决问题(顺便说一句,它们确实有用),那么这并不取决于问题是一天还是三年前提出的。赞同你提供的替代方案。 - nawfal

10

6
如果您需要在表单区域内获取当前位置(经过实验验证),请尝试以下方法:
Console.WriteLine(
    "Current mouse position in form's area is " + 
    (Control.MousePosition.X - this.Location.X - 8).ToString() +
    "x" + 
    (Control.MousePosition.Y - this.Location.Y - 30).ToString()
);

虽然在试验中发现了830这两个整数,但如果有人能够解释为什么这些数字有效,那将是非常棒的。


此外,还有另一种变体(考虑代码位于表单代码后台):

Point cp = PointToClient(Cursor.Position); // Get cursor's position according to form's area
Console.WriteLine("Cursor position: X = " + cp.X + ", Y = " + cp.Y);

3
   internal static class CursorPosition {
  [StructLayout(LayoutKind.Sequential)]
  public struct PointInter {
     public int X;
     public int Y;
     public static explicit operator Point(PointInter point) => new Point(point.X, point.Y);       
  }

  [DllImport("user32.dll")]
  public static extern bool GetCursorPos(out PointInter lpPoint);

  // For your convenience
  public static Point GetCursorPosition() {
     PointInter lpPoint;
     GetCursorPos(out lpPoint);
     return (Point) lpPoint;
  }

}


3

初始化当前光标。使用它获取X和Y的位置。

this.Cursor = new Cursor(Cursor.Current.Handle);
int posX = Cursor.Position.X;
int posY = Cursor.Position.Y;

1
在问题被提出时,这个答案还不适用,但是现在你可以使用命名空间为 System.Windows.Input 的静态方法 Mouse.GetPosition(IInputElement) ,该方法在 PresentationCore 组件中可用。这个方法从 .NET Framework 3.0 开始有效。更多信息请参见https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.mouse.getposition?view=windowsdesktop-6.0#System_Windows_Input_Mouse_GetPosition_System_Windows_IInputElement_ 示例:
// displayArea is a StackPanel and txtBoxMousePosition is
// a TextBox used to display the position of the mouse pointer.
Point position = Mouse.GetPosition(displayArea);
txtBoxMousePosition.Text = "X: " + position.X +
    "\n" +
    "Y: " + position.Y;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接