Answers:
您应该使用System.Windows.Forms.Cursor.Position:“一个表示光标在屏幕坐标中的位置的点。”
PointToClient
。
如果您不想引用Forms,则可以使用interop来获取光标位置:
using System.Runtime.InteropServices;
using System.Windows; // Or use whatever point class you like for the implicit cast operator
using System.Drawing;
/// <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;
}
Cursor.Position将获取鼠标的当前屏幕位置(如果位于Control中,MousePosition属性也将获得相同的值)。
要设置鼠标位置,您将不得不使用Cursor.Position
并为其赋予一个新的Point:
Cursor.Position = new Point(x, y);
您可以Main
在创建表单之前使用方法执行此操作。
要回答您的特定示例:
// 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>确定)
System.Windows.Forms.Control.MousePosition
获取鼠标光标在屏幕坐标中的位置。 “ Position属性与Control.MousePosition属性相同。”
要获得位置,请查看OnMouseMove事件。MouseEventArgs将为您提供x和y的位置...
protected override void OnMouseMove(MouseEventArgs mouseEv)
要设置鼠标位置,请使用Cursor.Position属性。
http://msdn.microsoft.com/zh-CN/library/system.windows.forms.cursor.position.aspx
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;
}
}
如果您需要获取表单区域中的当前位置(通过实验获得),请尝试:
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()
);
尽管通过实验发现了8和30个整数。
如果有人可以解释为什么这些数字^真是太棒了。
另外,还有另一个变体(考虑代码在Form的CodeBehind中):
Point cp = this.PointToClient(Cursor.Position); // Getting a cursor's position according form's area
Console.WriteLine("Cursor position: X = " + cp.X + ", Y = " + cp.Y);
您还必须具有以下导入才能导入DLL
using System.Runtime.InteropServices;
using System.Diagnostics;