zoukankan      html  css  js  c++  java
  • C#动态获取鼠标坐标

    .Net封装好的方法

    int Control.MousePosition.X;int 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 POINTpublic int x;   public int y;   public POINT()   {   }   public POINT(int x, int y)   {     this.x;     this.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([InOut] NativeMethods.POINT pt);

    到这里,已经很明了了,.Net封装好的Control.MousePosition,其实也是调用这个API的。

    如果你的程序讲究效率的话,应该使用原生态的API方法,虽然代码会多几行。

  • 相关阅读:
    IOS Block-Block块的使用与理解
    IOS 多线程03-GCD
    IOS 多线程01-线程基础知识
    JavaScript高级-定义函数(类)方法
    互联网技术笔试总通不过?leetcode刷对了么
    Redis 内存满了怎么办? Redis的内存淘汰策略
    SpringBoot项目优化和Jvm调优
    中台的末路
    Java 应用中的日志
    Spring Boot 支持https
  • 原文地址:https://www.cnblogs.com/wwwzzg168/p/3570678.html
Copyright © 2011-2022 走看看