該示例實現了控制鼠標的座標,分別用WIndows Api和.Net庫自帶的命令實現。
APi控制和獲取鼠標分別是: GetCursorPos和SetCursorPost。
下面是截圖:
using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Runtime.InteropServices;//
- namespace 獲取和設置鼠標的座標
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- /// <summary>
- /// 設置鼠標的座標
- /// </summary>
- /// <param name="x">橫座標</param>
- /// <param name="y">縱座標</param>
- [DllImport("User32")]
- public extern static void SetCursorPos(int x, int y);
- /// <summary>
- /// 獲取鼠標的座標
- /// </summary>
- /// <param name="lpPoint">傳址參數,座標point類型</param>
- /// <returns>獲取成功返回真</returns>
- [DllImport("User32")]
- public extern static bool GetCursorPos(ref Point lpPoint);
- private void button_go_Click(object sender, EventArgs e)
- {
- SetCursorPos(int.Parse(textBox_x.Text), (int.Parse(textBox_y.Text)));
- }
- Point p = new Point(1, 1);//定義存放獲取座標的point變量
- private void timer1_Tick(object sender, EventArgs e)
- {
- GetCursorPos(ref p);
- label_p.Text = "X:" + p.X + "\r\nY:" + p.Y;
- //label_p.Text = "X:" + Cursor.Position.X + "\r\nY:" + Cursor.Position.Y; //用C#自帶命令獲取
- }
- }
- }