.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方法,雖然代碼會多幾行。