C# 获取鼠标位置

.Net封装好的方法

int x = Control.MousePosition.X;
int y = Control.MousePosition.Y;

用API方法

using System.Runtime.InteropServices;
Point p;
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out Point pt);
private void timer1_Tick(object sender, EventArgs e)
{
   GetCursorPos(out p);
   label1.Text = p.X.ToString();//X坐标
   label2.Text = p.Y.ToString();//Y坐标
}

利用Reflector去查看Control.MousePosition属性,其源代码如下:

public static Point MousePosition
{
   get
   {
      NativeMethods.POINT pt = new NativeMethods.POINT();
      UnsafeNativeMethods.GetCursorPos(pt);
      return new Point(pt.x, pt.y);
   }
}

其中NativeMethods.POINT类,它的构造代码如下:

public class POINT
{
   public int x;
   public int y;
   public POINT()
   {
   }

   public POINT(int x, int y)
   {
     this.x = x;
     this.y = y;
   }
}

它和System.Drawing.Point类的构造是一样的,所以上面用API的方法中,我们可以直接用System.Drawing.Point类去声明一个对象。

再看UnsafeNativeMethods.GetCursorPos(pt); 这句代码,它的GetCursorPos方法源码如下:

[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern bool GetCursorPos([In, Out] NativeMethods.POINT pt);

到这里,已经很明了了,.Net封装好的Control.MousePosition,其实也是调用这个API的。

如果你的程序讲究效率的话,应该使用原生态的API方法,虽然代码会多几行。

原文地址:https://www.cnblogs.com/DotNetCSharp/p/2034884.html