模拟按键精灵的功能实现 - (第十七讲)
视频讲解如下:
CSDN源码下载
https://download.csdn.net/download/gs1069405343/19640984
网盘下载,提取码:ysrp
https://pan.baidu.com/s/1ADy91rrGdHwRl_gkuJFI0Q
这里给大家讲解一下如何实现模拟按键精灵的功能
实现效果:记录用户的操作步骤,程序能够自动执行。
演示效果如下:

using Gma.System.MouseKeyHook;
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace mouse
{
public class mouse
{
/// <summary>
/// 按键操作
/// </summary>
public int key { get; set; } = 0;
[DllImport("user32.dll")]
static extern void mouse_event(int flags, int dX, int dY, int buttons, int extraInfo);
const int MOUSEEVENTF_MOVE = 0x1;//模拟鼠标移动
const int MOUSEEVENTF_LEFTDOWN = 0x2;//
const int MOUSEEVENTF_LEFTUP = 0x4;
const int MOUSEEVENTF_RIGHTDOWN = 0x8;
const int MOUSEEVENTF_RIGHTUP = 0x10;
const int MOUSEEVENTF_MIDDLEDOWN = 0x20;
const int MOUSEEVENTF_MIDDLEUP = 0x40;
const int MOUSEEVENTF_WHEEL = 0x800;
const int MOUSEEVENTF_ABSOLUTE = 0x8000;
/// <summary>
/// 屏幕分辨率高
/// </summary>
public int windows_height { get; set; } = 1080;
/// <summary>
/// 屏幕分辨率宽
/// </summary>
public int windows_width { get; set; } = 1920;
/// <summary>
/// 控制鼠标移动到指定位置
/// </summary>
/// <param name="start"></param>
/// <param name="End"></param>
/// <param name="speed"></param>
public void mouse_move(Point start, Point End, int speed)
{
int startX = start.X;
int startY = start.Y;
int EndX = End.X;
int EndY = End.Y;
int x = startX;
int y = startY;
while (x != EndX || y != EndY)
{
if (startX > EndX && x != EndX)
{
x -= speed;
if (x <= EndX) x = EndX;
}
if (startX < EndX && x != EndX)
{
x += speed;
if (x >= EndX) x = EndX;
}
if (startY > EndY && y != EndY)
{
y -= speed;
if (y <= EndY) y = EndY;
}
if (startY < EndY && y != EndY)
{
y += speed;
if (y >= EndY) y = EndY;
}
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, x * 65536 / windows_width, y * 65536 / windows_height, 0, 0);
Thread.Sleep(100);
}
}
public void SetEndCoor(Point end)
{
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, end.X * 65536 / windows_width, end.Y * 65536 / windows_height, 0, 0);
}
/// <summary>
/// 按下鼠标左键
/// </summary>
public void mouse_click()
{
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
private IKeyboardMouseEvents m_GlobalHook;
public void Subscribe()
{
m_GlobalHook = Hook.GlobalEvents();
m_GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
}
private void GlobalHookMouseDownExt(object sender, MouseEventExtArgs e)
{
if (e.Button == MouseButtons.Left)
{
Console.WriteLine("左键");
key = 1;
}
if (e.Button == MouseButtons.Right)
{
Console.WriteLine("右键");
m_GlobalHook.MouseDownExt -= GlobalHookMouseDownExt;
m_GlobalHook.Dispose();
key = 2;
}
}
}
}