C#获取鼠标的坐标

该示例实现了控制鼠标的坐标,分别用WIndows Api和.Net库自带的命令实现。

 APi控制和获取鼠标分别是:   GetCursorPos和SetCursorPost。

下面是截图:

 

using System;  

  1. using System.Collections.Generic;  
  2. using System.ComponentModel;  
  3. using System.Data;  
  4. using System.Drawing;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. using System.Runtime.InteropServices;//   
  9.   
  10. namespace 获取和设置鼠标的坐标  
  11. {  
  12.     public partial class Form1 : Form  
  13.     {  
  14.         public Form1()  
  15.         {  
  16.             InitializeComponent();  
  17.         }  
  18.   
  19.         /// <summary>   
  20.         /// 设置鼠标的坐标   
  21.         /// </summary>   
  22.         /// <param name="x">横坐标</param>   
  23.         /// <param name="y">纵坐标</param>   
  24.         [DllImport("User32")]  
  25.         public extern static void SetCursorPos(int x, int y);  
  26.   
  27.         /// <summary>   
  28.         /// 获取鼠标的坐标   
  29.         /// </summary>   
  30.         /// <param name="lpPoint">传址参数,坐标point类型</param>   
  31.         /// <returns>获取成功返回真</returns>   
  32.         [DllImport("User32")]  
  33.         public extern static bool GetCursorPos(ref Point lpPoint);  
  34.   
  35.   
  36.         private void button_go_Click(object sender, EventArgs e)  
  37.         {                    
  38.             SetCursorPos(int.Parse(textBox_x.Text), (int.Parse(textBox_y.Text)));              
  39.         }  
  40.   
  41.         Point p = new Point(1, 1);//定义存放获取坐标的point变量   
  42.         private void timer1_Tick(object sender, EventArgs e)  
  43.         {  
  44.   
  45.             GetCursorPos(ref p);  
  46.             label_p.Text = "X:" + p.X + "\r\nY:" + p.Y;  
  47.             //label_p.Text = "X:" + Cursor.Position.X + "\r\nY:" + Cursor.Position.Y; //用C#自带命令获取   
  48.         }  
  49.     }  
  50. }  

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值