原理很简单,发送mouse_event 消息(具体参数信息可查msdn)
为了方便控制,在系统中注册热键
RegisterHotKey 注册热键
UnregisterHotKey 释放热键
有代码有真相:
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
{
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(
IntPtr hWnd, // handle to window
int id, // hot key identifier
KeyModifiers fsModifiers, // key-modifier options
Keys vk // virtual-key code
);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(
IntPtr hWnd, // handle to window
int id // hot key identifier
);
[Flags()]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
[DllImport("user32.dll")]
static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
[Flags]
enum MouseEventFlag : uint
{
Move = 0x0001,
LeftDown = 0x0002,
LeftUp = 0x0004,
RightDown = 0x0008,
RightUp = 0x0010,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
XDown = 0x0080,
XUp = 0x0100,
Wheel = 0x0800,
VirtualDesk = 0x4000,
Absolute = 0x8000
}
bool hotkeyRegist; //标记热键注册是否成功
bool _keyDown; //标记是否开始鼠标点击
public Form1()
{
InitializeComponent();
hotkeyRegist = _keyDown = false;
}
private void Form1_Load(object sender, EventArgs e)
{
hotkeyRegist = RegisterHotKey(Handle, 100, KeyModifiers.None, Keys.F6);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
UnregisterHotKey(Handle, 100);
}
protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
switch (m.Msg)
{
case WM_HOTKEY:
{
if (this.hotkeyRegist)
{
if (this._keyDown)
{
this.timer1.Stop();
}
else
{
int inttmp;
try
{
inttmp=Convert.ToInt32(this.textBox1.Text);
}
catch
{
inttmp=1000;
}
this.timer1.Interval = inttmp;
this.timer1.Start();
}
this._keyDown = !this._keyDown;
}
break;
}
}
base.WndProc(ref m);
}
private void timer1_Tick(object sender, EventArgs e)
{
mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
System.Threading.Thread.Sleep(10);
mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
}
}
}
注:
[flags] 表示位域
查了一下,说明如下:
.NET中的枚举我们一般有两种用法,一是表示唯一的元素序列,例如一周里的各天;还有就是用来表示多种复合的状态。这个时候一般需要为枚举加上[Flags]特性标记为位域,例如:
[Flags]
enum Styles{
ShowBorder = 1, //是否显示边框
ShowCaption = 2, //是否显示标题
ShowToolbox = 4 //是否显示工具箱
}
这样我们就可以用"或"运算符组合多个状态,例如
myControl.Style = Styles.ShowBorder | Styles.ShowCaption;