. Net encapsulated Method
int x = Control.MousePosition.X;int y = Control.MousePosition.Y;
API method
using System.Runtime.InteropServices;
Point p; [DllImport ("user32.dll")] public static extern bool GetCursorPos (out Point pt); private void timereffectick (object sender, EventArgs e) {GetCursorPos (out p ); label1.Text = p. x. toString (); // X coordinate label2.Text = p. y. toString (); // Y coordinate}
Use Reflector to view the Control. MousePosition attribute. The source code is as follows:
public static Point MousePosition{ get { NativeMethods.POINT pt = new NativeMethods.POINT(); UnsafeNativeMethods.GetCursorPos(pt); return new Point(pt.x, pt.y); }}
The NativeMethods. POINT class has the following constructor code:
public class POINT{ public int x; public int y; public POINT() { } public POINT(int x, int y) { this.x = x; this.y = y; }}
It is the same as the construction of the System. Drawing. Point class. Therefore, in the above API method, we can directly use the System. Drawing. Point class to declare an object.
Check againUnsafeNativeMethods.GetCursorPos (pt );This code, itsGetCursorPos MethodThe source code is as follows:
[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]public static extern bool GetCursorPos([In, Out] NativeMethods.POINT pt);
At this point, it is clear that the Control. MousePosition encapsulated by. Net actually calls this API.
If your program is efficient, you should use the original ecological API method, although the Code will be several more lines.