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方法,虽然代码会多几行。

  • 相关阅读:
    How to Build Office Developer Tools Projects with TFS Team Build 2012
    查看hyper-v主机mac地址
    “Stamping” PDF Files Downloaded from SharePoint 2010
    PostgreSQL体系基本概念
    PostgreSQL 安装
    HDFS+MapReduce+Hive+HBase十分钟快速入门
    光照计算公式
    游戏中的碰撞
    数组
    扑克牌概率
  • 原文地址:https://www.cnblogs.com/DotNetCSharp/p/2034884.html
Copyright © 2011-2022 走看看