zoukankan      html  css  js  c++  java
  • 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方法,虽然代码会多几行。

  • 相关阅读:
    比较两个树是否相同
    将一个字符串转换成一个整数
    求数组中第一个重复数字
    Redis之哨兵机制(sentinel)——配置详解及原理介绍
    ==和equals的区别
    求一个数的立方根
    检测应用版本
    【转】UITableViewCell自适应高度 UILabel自适应高度和自动换行
    iOS7中Cell高度 Label高度自适应
    MarsEdit 快速插入代码
  • 原文地址:https://www.cnblogs.com/DotNetCSharp/p/2034884.html
Copyright © 2011-2022 走看看