
一、项目搭建
1.1、创建
1.2、界面设计
private void button1_Click(object sender, EventArgs e)
{
}
二、功能实现
2.1、类型库调用
[DllImport("User32")]
public extern static void mouse_event(int dwFlags, int dx, int dy, int dwData, IntPtr dwExtraInfo);
[DllImport("User32")]
public extern static void SetCursorPos(int x, int y);
[DllImport("User32")]
public extern static bool GetCursorPos(out POINT p);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
}
2.2、窗口句柄定义
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr wnd, int id, MODKEY mode, Keys vk);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr wnd, int id);
[Flags()]
public enum MODKEY
{
None = 0,
ALT = 0x0001,
CTRL = 0x0002,
SHIFT = 0x0004,
WIN = 0x0008,
}
private NotifyIcon notifyIcon = null;
public enum MouseEventFlags
{
Move = 0x0001,
LeftDown = 0x0002,
LeftUp = 0x0004,
RightDown = 0x0008,
RightUp = 0x0010,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
Wheel = 0x0800,
Absolute = 0x8000
}
2.3、线程处理
private void button1_Click(object sender, EventArgs e)
{
// 启动新线程执行循环操作
Thread thread = new Thread(new ThreadStart(Loop));
thread.Start();
}
private void Loop()
{
int count = Convert.ToInt32(this.textBox1.Text);
for (int i = 0; i < count; i++)
{
// 使用 Invoke 方法将 Label 的 Text 属性设置为当前的值
this.Invoke(new Action(() =>
{
label1.Text = "已模拟点击鼠标点击次数:"+i.ToString();
}));
Thread.Sleep(1); // 模拟耗时操作
}
}

//隐藏主窗体
this.Hide();
//实例化一个NotifyIcon对象
notifyIcon = new NotifyIcon();
//托盘图标气泡显示的内容
notifyIcon.BalloonTipText = "正在后台运行";
//托盘图标显示的内容
notifyIcon.Text = "鼠标自动点击器";
//注意:下面的路径可以是绝对路径、相对路径。但是需要注意的是:文件必须是一个.ico格式
//notifyIcon.Icon = new System.Drawing.Icon("F:/renjiashuo/program/AutoClickMouse/AutoClickMouse/mouse.ico");
ComponentResourceManager resources = new ComponentResourceManager(typeof(AutoClickMouseLeftButton));
notifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
//true表示在托盘区可见,false表示在托盘区不可见
notifyIcon.Visible = true;
//气泡显示的时间(单位是毫秒)
notifyIcon.ShowBalloonTip(5000);
notifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(notifyIcon_MouseClick);
2.4、快捷键
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0312)
{
switch (m.WParam.ToInt32())
{
case 10:
this.BT_Start_Click(null,null);
break;
case 11:
this.BT_Stop_Click(null, null);
break;
default:
break;
}
return;
}
base.WndProc(ref m);
}