1. 程式人生 > 實用技巧 >C#實現模擬滑鼠點選事件(點選桌面的其他程式 )

C#實現模擬滑鼠點選事件(點選桌面的其他程式 )

註釋感覺已經很清楚了,有不懂的歡迎評論

 1 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Hide();
}
/// <summary>
/// 引用user32.dll動態連結庫(windows api),
/// 使用庫中定義 API:SetCursorPos
/// </summary>
[DllImport("user32.dll")]
private static extern int SetCursorPos(int x, int y);
/// <summary>
/// 移動滑鼠到指定的座標點
/// </summary>
public void MoveMouseToPoint(Point p)
{
SetCursorPos(p.X, p.Y);
}
/// <summary>
/// 設定滑鼠的移動範圍
/// </summary>
public void SetMouseRectangle(Rectangle rectangle)
{
System.Windows.Forms.Cursor.Clip = rectangle;
}
/// <summary>
/// 設定滑鼠位於螢幕中心
/// </summary>
public void SetMouseAtCenterScreen()
{
//當前螢幕的寬高
int winHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
int winWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
//設定滑鼠的x,y位置
loginx = winWidth / * ;
loginy = winHeight / + ;
Point centerP = new Point(loginx, loginy);
//移動滑鼠
MoveMouseToPoint(centerP);
}
//點選事件
[DllImport("User32")]
//下面這一行對應著下面的點選事件
// public extern static void mouse_event(int dwFlags, int dx, int dy, int dwData, IntPtr dwExtraInfo);
public extern static void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
public const int MOUSEEVENTF_LEFTDOWN = 0x2;
public const int MOUSEEVENTF_LEFTUP = 0x4;
public enum MouseEventFlags
{
Move = 0x0001, //移動滑鼠
LeftDown = 0x0002,//模擬滑鼠左鍵按下
LeftUp = 0x0004,//模擬滑鼠左鍵抬起
RightDown = 0x0008,//滑鼠右鍵按下
RightUp = 0x0010,//滑鼠右鍵抬起
MiddleDown = 0x0020,//滑鼠中鍵按下
MiddleUp = 0x0040,//中鍵抬起
Wheel = 0x0800,
Absolute = 0x8000//標示是否採用絕對座標
}
//滑鼠將要到的x,y位置
public static int loginx, loginy;
private void Form1_Load(object sender, EventArgs e)
{ //移動滑鼠
SetMouseAtCenterScreen(); //mouse_event((int)(MouseEventFlags.LeftDown | MouseEventFlags.Absolute), loginx, loginy, 0, IntPtr.Zero); //mouse_event((int)(MouseEventFlags.LeftUp | MouseEventFlags.Absolute), loginx, loginy, 0, IntPtr.Zero);
//點選兩次
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, loginx, loginy, , ); mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, loginx, loginy, , ); }
}
}