C # Dynamically Retrieve mouse coordinates

Source: Internet
Author: User

. 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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.