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

 

 

發佈了9 篇原創文章 · 獲贊 4 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章