Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说
按键精灵录制键盘鼠标动作_鼠标录制,希望能够帮助你!!!。
是一个非常实用的键盘鼠标脚本录制工具,通过它你可以轻松地进行脚本录制,简单易用,不需要任何编程知识就能做出功能强大的脚本,只要你在电脑前用双手可以完成的动作,都可以替你完成。
下载软件
1.运行录制脚步时模拟过程 比按键精灵 更加流畅,还原度更高,以模拟鼠标在画图软件里画画还原为例.
2.支持录制脚步 可以在按键精灵运行 ,按键精灵 录制鼠标按键键盘脚步也可以复制到记录框 在我这个里运行.其他找色等就不支持
3.免费 无广告.按键精灵录制生成的exe文件会插入广告 还有登陆注册 比较麻烦
代码引用了github 开源 神龙辅助工具 C#
GitHub - respost/DragonHelperTool: 一个非常实用的键盘鼠标脚本录制工具,通过它你可以轻松地进行脚本录制,简单易用。一个非常实用的键盘鼠标脚本录制工具,通过它你可以轻松地进行脚本录制,简单易用。. Contribute to respost/DragonHelperTool development by creating an account on GitHub.https://github.com/respost/DragonHelperTool
//设置键盘勾子 khl = new KeyboardHookListener(new MouseKeyboardActivityMonitor.WinApi.GlobalHooker()); // 键盘按下事件 ,通过记录按下的时间和按键 保存到文件 khl.KeyDown += (a, b) => { if (currState == KState.Recording && checkBox2.Checked) { string s = "", d = "", m = ""; recordList.Add(TimeEx.GetCurrTimestamp()); d = "Delay " + AndLastTime(); s = "KeyDown \"" + b.KeyData + "\", 1"; } }; khl.Enabled = true; 运行脚本时 循环读取文件 读取每行 运行延迟 和 模拟按键按下 Thread.Sleep((int)(delayTime)); if (rf.mouseX == 0) {//键盘事件 Keys key = (Keys)rf.keyNumber; if (rf.keyState == 0) { KeyboardHelper.KeyDown(key); }
using MouseKeyboardActivityMonitor; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using Wb.EventSystem; using 神龙辅助工具; namespace KeyboardRecord_V2 { public partial class Form1 : Form { public static Form1 instance = null; private MouseHookListener mhl; private KeyboardHookListener khl; RecordFileManage rm; public static TextBox textBox1Static; private static bool mouseLeftDown = false; private static bool mouseRightDown = false; private static bool mouseMiddleDown = false; public static List<MyThread> myThreads = new List<MyThread>(); /// <summary> /// 是否有鼠标按键被按下 /// </summary> private static bool mouseIsDown { get { return mouseLeftDown || mouseRightDown || mouseMiddleDown; } } /// <summary> /// 循环遍历窗体中的所有控件。使用if语句判断控件是否为按钮控件,如果是,禁用启用所有按键 /// </summary> public bool Button_Enable_All { get { return false; } set { // 查找窗体中的所有按钮 Button[] buttons = this.Controls.OfType<Button>().ToArray(); // 遍历所有按钮 foreach (Button button in buttons) { button.Enabled = value; // 打印按钮名称 Console.WriteLine(button.Name); } } } private volatile bool flag = false; public static KState currState = KState.Null; int pp0p3p = 0; string savePath = System.AppDomain.CurrentDomain.BaseDirectory + @"Recorder\"; public string saveFilePath = ""; public string SaveNewTypePath = System.AppDomain.CurrentDomain.BaseDirectory; string saveNewTypeFilePath = ""; public Form1() { InitializeComponent(); instance = this; SetKeyboradHookEvent(); // 注册事件 EventSystem.RegisterEvent(EGameEvent.append_textbox1_text, (a, new_text) => { textBox1.Append((new_text[0] as string)); }); textBox1Static = textBox1; textBox1.AddScrollBars_WordWrap_Multiline_v2(); //判断该路径下文件夹是否存在,不存在的情况下新建文件夹 if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } if (!Directory.Exists(SaveNewTypePath)) { Directory.CreateDirectory(SaveNewTypePath); } saveFilePath = WinformExtension.GetRegistData("saveFilePath") as string; textBox4.Text = Path.GetFileName(saveFilePath); autoFilePath = WinformExtension.GetRegistData("autoFilePath") as string; if (File.Exists(autoFilePath)) { textBox3.Text = autoFilePath; } var checkBox3_Checked = WinformExtension.GetRegistData("checkBox3_Checked"); if (checkBox3_Checked != null) { checkBox3.Checked = checkBox3_Checked.ToString() == "True" ? true : false; if (checkBox3.Checked) { if (File.Exists(autoFilePath)) { MyThread thread1 = new MyThread(); thread1.Bind(RecordFileManage.RunFile, autoFilePath); thread1.Start(); myThreads.Add(thread1); } } } #region comboBox1 ComboBox combBox9527 = null; combBox9527 = comboBox1; // 将枚举类型的所有值添加到下拉选择框中 foreach (Keys gender in Enum.GetValues(typeof(Keys))) { combBox9527.Items.Add(gender); } //这两个属性的区别在于它们分别返回显示文本和所选项的值 //comboBox1.DisplayMember 返回显示文本 //comboBox1.SelectedItem 返回所选项的值 combBox9527.SelectedItem = comboBox1_key = Keys.F6; combBox9527.DisplayMember = Enum.GetName(typeof(Keys), Keys.F6); combBox9527 = comboBox2; // 将枚举类型的所有值添加到下拉选择框中 foreach (Keys gender in Enum.GetValues(typeof(Keys))) { combBox9527.Items.Add(gender); } //这两个属性的区别在于它们分别返回显示文本和所选项的值 //comboBox1.DisplayMember 返回显示文本 //comboBox1.SelectedItem 返回所选项的值 combBox9527.SelectedItem = comboBox2_key = Keys.F7; combBox9527.DisplayMember = Enum.GetName(typeof(Keys), Keys.F7); combBox9527 = comboBox3; // 将枚举类型的所有值添加到下拉选择框中 foreach (Keys gender in Enum.GetValues(typeof(Keys))) { combBox9527.Items.Add(gender); } //这两个属性的区别在于它们分别返回显示文本和所选项的值 //comboBox1.DisplayMember 返回显示文本 //comboBox1.SelectedItem 返回所选项的值 combBox9527.SelectedItem = comboBox3_key = Keys.F8; combBox9527.DisplayMember = Enum.GetName(typeof(Keys), Keys.F8); #endregion #region 窗口居中 // 获取屏幕尺寸 int screenWidth = Screen.PrimaryScreen.WorkingArea.Width; int screenHeight = Screen.PrimaryScreen.WorkingArea.Height; // 计算窗口居中的位置 int left = (screenWidth - this.Width) / 2; int top = (screenHeight - this.Height) / 2; // 设置窗口位置 this.StartPosition = FormStartPosition.Manual; this.Location = new Point(left, top); #endregion // 确保 Form 控件的 KeyPreview 属性设置为 true。这样,Form 窗口会在其他控件之前接收所有按键事件。 //确保 Form 控件有焦点,否则它将无法接收按键事件。 this.KeyPreview = true; this.Focus(); } public void RunRecordScript( ) { Form1.instance.Button_Enable_All = false; currState = KState.Runing; MyThread thread1 = new MyThread(); thread1.Bind(RecordFileManage.RunFile, saveFilePath); thread1.Start(); myThreads.Add(thread1); } public static void StopRunRecordScript() { Form1.instance.Button_Enable_All = true; currState = KState.Null; Form1.instance.SetTextSafe("键盘记录器(执行完毕)"); myThreads.ForEach(x => { x.Stop(); }); } long recordStartTime = 0; long lastTimer = 0; List<long> recordList = new List<long>(10000); long AndLastTime() { if (recordList.Count == 0) return 108; var currTime = recordList[recordList.Count - 1]; var delayTime = currTime - recordStartTime - lastTimer; lastTimer = currTime - recordStartTime; if (delayTime <= 0) { return 186; throw new Exception("delayTime <= 0,在某些情况下先按的按键事件没有及时返回,到后面才返回,导致减法为负数.解决办法:事件根据时间戳排序在减"); } return delayTime; } private void button1_Click(object sender, EventArgs e) { StartRecord(); } private void button2_Click(object sender, EventArgs e) { StopRecord(); } private void button3_Click(object sender, EventArgs e) { string filePath = FolderBrowserHelper.SelectFile(savePath); //MyThread thread1 = new MyThread(RecordFileManage.RunFile, filePath); //thread1.Start(); //myThreads.Add(thread1); } void StartRecord() { button1.Text = "已开始录制"; button1.Enabled = false; button2.Enabled = true; checkBox1.Enabled = false; checkBox2.Enabled = false; checkBox4.Enabled = false; textBox1.ReadOnly = true; currState = KState.Recording; recordStartTime = TimeEx.GetCurrTimestamp(); saveFilePath = savePath + TimeEx.GetCurrTimeStr() + ".txt"; WinformExtension.SetRegistData("saveFilePath", saveFilePath); string fileName = Path.GetFileName(saveFilePath); textBox4.Text = fileName; rm = new RecordFileManage(recordStartTime, saveFilePath); SetMouseHookEvent(); if (checkBox1.Checked) { mhl.Enabled = true; } textBox1.AddScrollBars_WordWrap_Multiline_v2(); } void StopRecord() { if (currState != KState.Recording) return; button1.Text = "⚫ 开始录制"; button2.Enabled = false; button1.Enabled = true; checkBox1.Enabled = true; checkBox2.Enabled = true; checkBox4.Enabled = true; textBox1.ReadOnly = false; textBox1.ReduceScrollBars_WordWrap_Multiline(); currState = KState.Null; if(mhl!=null) mhl.Enabled = false; rm.SaveFile(); } /// <summary> /// 设置键盘勾子事件 /// </summary> void SetKeyboradHookEvent() { //设置键盘勾子 khl = new KeyboardHookListener(new MouseKeyboardActivityMonitor.WinApi.GlobalHooker()); khl.KeyDown += (a, b) => { if (currState == KState.Recording && checkBox2.Checked) { string s = "", d = "", m = ""; recordList.Add(TimeEx.GetCurrTimestamp()); d = "Delay " + AndLastTime(); s = "KeyDown \"" + b.KeyData + "\", 1"; EventSystem.SendEvent(EGameEvent.append_textbox1_text, d); EventSystem.SendEvent(EGameEvent.append_textbox1_text, s); rm.AddKeyboard(b.KeyData, 0, TimeEx.GetCurrTimestamp()); } HotKey(b); }; khl.KeyUp += (a, b) => { if (currState == KState.Recording && checkBox2.Checked) { string s = "", d = "", m = ""; recordList.Add(TimeEx.GetCurrTimestamp()); d = "Delay " + AndLastTime(); s = "KeyUp \"" + b.KeyData + "\", 1"; EventSystem.SendEvent(EGameEvent.append_textbox1_text, d); EventSystem.SendEvent(EGameEvent.append_textbox1_text, s); rm.AddKeyboard(b.KeyData, 2, TimeEx.GetCurrTimestamp()); } }; khl.Enabled = true; } void HotKey(KeyEventArgs e) { if (e.KeyCode == comboBox1_key && currState == KState.Null) { StartRecord(); } if (e.KeyCode == comboBox2_key) { if (currState == KState.Recording) { StopRecord(); } if (currState == KState.Runing) { StopRunRecordScript(); } } if (e.KeyCode == comboBox3_key && currState == KState.Null) { RunRecordScript(); } } /// <summary> /// 设置鼠标勾子事件 /// </summary> void SetMouseHookEvent() { //设置鼠标勾子 mhl = new MouseHookListener(new MouseKeyboardActivityMonitor.WinApi.GlobalHooker()); if (checkBox4.Checked) { mhl.MouseMove += (a, b) => { if (mouseIsDown) { string s = "", d = "", m = ""; recordList.Add(TimeEx.GetCurrTimestamp()); m = "MoveTo " + b.X + ", " + b.Y; d = "Delay " + AndLastTime(); EventSystem.SendEvent(EGameEvent.append_textbox1_text, d); EventSystem.SendEvent(EGameEvent.append_textbox1_text, m); rm.AddMouse(b.Button, 0, TimeEx.GetCurrTimestamp(), b.X, b.Y); } }; } mhl.MouseDownExt += (a, b) => { string s = "", d = "", m = ""; switch (b.Button) { case MouseButtons.None: break; case MouseButtons.Left: recordList.Add(TimeEx.GetCurrTimestamp()); d = "Delay " + AndLastTime(); m = "MoveTo " + b.X + ", " + b.Y; s = "Left" + "Down" + " 1"; EventSystem.SendEvent(EGameEvent.append_textbox1_text, d); EventSystem.SendEvent(EGameEvent.append_textbox1_text, m); EventSystem.SendEvent(EGameEvent.append_textbox1_text, s); rm.AddMouse(b.Button, 0, TimeEx.GetCurrTimestamp(), b.X, b.Y); mouseLeftDown = true; break; case MouseButtons.Right: recordList.Add(TimeEx.GetCurrTimestamp()); d = "Delay " + AndLastTime(); m = "MoveTo " + b.X + ", " + b.Y; s = "Right" + "Down" + " 1"; EventSystem.SendEvent(EGameEvent.append_textbox1_text, d); EventSystem.SendEvent(EGameEvent.append_textbox1_text, m); EventSystem.SendEvent(EGameEvent.append_textbox1_text, s); rm.AddMouse(b.Button, 0, TimeEx.GetCurrTimestamp(), b.X, b.Y); mouseRightDown = true; break; case MouseButtons.Middle: recordList.Add(TimeEx.GetCurrTimestamp()); d = "Delay " + AndLastTime(); m = "MoveTo " + b.X + ", " + b.Y; s = "Middle" + "Down" + " 1"; EventSystem.SendEvent(EGameEvent.append_textbox1_text, d); EventSystem.SendEvent(EGameEvent.append_textbox1_text, m); EventSystem.SendEvent(EGameEvent.append_textbox1_text, s); rm.AddMouse(b.Button, 0, TimeEx.GetCurrTimestamp(), b.X, b.Y); mouseMiddleDown = true; break; case MouseButtons.XButton1: break; case MouseButtons.XButton2: break; } }; mhl.MouseUp += (a, b) => { string s = "", d = "", m = ""; switch (b.Button) { case MouseButtons.None: break; case MouseButtons.Left: recordList.Add(TimeEx.GetCurrTimestamp()); d = "Delay " + AndLastTime(); m = "MoveTo " + b.X + ", " + b.Y; s = "Left" + "Up" + " 1"; EventSystem.SendEvent(EGameEvent.append_textbox1_text, d); EventSystem.SendEvent(EGameEvent.append_textbox1_text, m); EventSystem.SendEvent(EGameEvent.append_textbox1_text, s); rm.AddMouse(b.Button, 2, TimeEx.GetCurrTimestamp(), b.X, b.Y); mouseLeftDown = false; break; case MouseButtons.Right: recordList.Add(TimeEx.GetCurrTimestamp()); d = "Delay " + AndLastTime(); m = "MoveTo " + b.X + ", " + b.Y; s = "Right" + "Up" + " 1"; EventSystem.SendEvent(EGameEvent.append_textbox1_text, d); EventSystem.SendEvent(EGameEvent.append_textbox1_text, m); EventSystem.SendEvent(EGameEvent.append_textbox1_text, s); rm.AddMouse(b.Button, 2, TimeEx.GetCurrTimestamp(), b.X, b.Y); mouseRightDown = false; break; case MouseButtons.Middle: recordList.Add(TimeEx.GetCurrTimestamp()); d = "Delay " + AndLastTime(); m = "MoveTo " + b.X + ", " + b.Y; s = "Middle" + "Up" + " 1"; EventSystem.SendEvent(EGameEvent.append_textbox1_text, d); EventSystem.SendEvent(EGameEvent.append_textbox1_text, m); EventSystem.SendEvent(EGameEvent.append_textbox1_text, s); rm.AddMouse(b.Button, 2, TimeEx.GetCurrTimestamp(), b.X, b.Y); mouseMiddleDown = false; break; case MouseButtons.XButton1: break; case MouseButtons.XButton2: break; } }; } private void checkBox1_CheckedChanged(object sender, EventArgs e) { } private void checkBox2_CheckedChanged(object sender, EventArgs e) { } private void button4_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("notepad.exe", saveFilePath); } private void button5_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("explorer.exe", savePath); } string autoFilePath; private void button6_Click(object sender, EventArgs e) { autoFilePath = FolderBrowserHelper.SelectFile(savePath); textBox3.Text = autoFilePath; WinformExtension.SetRegistData("autoFilePath", autoFilePath); } bool checkBox3_Checked; private void checkBox3_CheckedChanged(object sender, EventArgs e) { WinformExtension.SetRegistData("checkBox3_Checked", checkBox3.Checked); } private void d(object sender, EventArgs e) { } private void button7_Click(object sender, EventArgs e) { //MyThread thread1 = new MyThread(RecordFileManage.RunFile, saveFilePath); //thread1.Start(); } private void button8_Click(object sender, EventArgs e) { //MyThread thread1 = new MyThread(RecordFileManage.RunFile, autoFilePath); //thread1.Start(); //myThreads.Add(thread1); currState = KState.Runing; } string fixSaveFilePath = ""; private void button9_Click(object sender, EventArgs e) { fixSaveFilePath = SaveNewTypePath + TimeEx.GetCurrTimeStr() + "_KeyboradRecordFile" + ".txt"; saveFilePath = fixSaveFilePath; textBox4.Text = saveFilePath; var rfm = new RecordFileManage_V2(fixSaveFilePath); rfm.SaveFile(); } private void button10_Click(object sender, EventArgs e) { WinformExtension.OpenFile(fixSaveFilePath); } private void button11_Click(object sender, EventArgs e) { HighPrecisionTimer.Test(); textBox1.Text = ""; } private void button12_Click(object sender, EventArgs e) { MyThread thread1 = new MyThread(); thread1.Bind(RecordFileManage_V2.Run, textBox1.Text); thread1.Start(); myThreads.Add(thread1); } private void button13_Click(object sender, EventArgs e) { RunRecordScript(); } private void button12_MouseHover(object sender, EventArgs e) { } private void button9_MouseHover(object sender, EventArgs e) { //Point relativePos = button9.PointToClient(MousePosition); //将屏幕坐标转换为控件内的相对坐标 toolTip1.Show("该文件只能在记录框里执行,其他运行文件按钮不支持\nThis file can only be executed within the logging framework. It is not supported by other executable files.", button9,0,-30,2000); } private void button14_Click(object sender, EventArgs e) { } private void label3_Click(object sender, EventArgs e) { } private void button14_Click_1(object sender, EventArgs e) { MyThreadExample.thread1.Stop(); } Form2 form2; private void button14_Click_2(object sender, EventArgs e) { form2 = new Form2(); string fileName = Path.GetFileName(saveFilePath); form2.textBox1.Text = fileName; form2.Show(); } private void textBox5_TextChanged(object sender, EventArgs e) { } private void comboBox1_TextChanged(object sender, EventArgs e) { } private void comboBox2_TextChanged(object sender, EventArgs e) { } private void comboBox1_Enter(object sender, EventArgs e) { } private void comboBox3_KeyPress(object sender, KeyPressEventArgs e) { } Keys comboBox1_key, comboBox2_key, comboBox3_key; private void label1_Click(object sender, EventArgs e) { } private void Form1_KeyDown(object sender, KeyEventArgs e) { } private void comboBox3_KeyDown(object sender, KeyEventArgs e) { var combBox9527 = comboBox1; if (combBox9527.Focused) { // 将选中项设置为用户按下的键 combBox9527.SelectedItem = e.KeyCode; // 设置显示文本为键的名称 combBox9527.DisplayMember = Enum.GetName(typeof(Keys), e.KeyCode); comboBox1_key = e.KeyCode; } combBox9527 = comboBox2; if (combBox9527.Focused) { // 将选中项设置为用户按下的键 combBox9527.SelectedItem = e.KeyCode; // 设置显示文本为键的名称 combBox9527.DisplayMember = Enum.GetName(typeof(Keys), e.KeyCode); comboBox2_key = e.KeyCode; } combBox9527 = comboBox3; if (combBox9527.Focused) { // 将选中项设置为用户按下的键 combBox9527.SelectedItem = e.KeyCode; // 设置显示文本为键的名称 combBox9527.DisplayMember = Enum.GetName(typeof(Keys), e.KeyCode); comboBox3_key = e.KeyCode; } } } public class RecordFile { /// <summary> /// keyDown =0 ,keyUp =1 /// </summary> public int keyState; /// <summary> /// 哪个按键被按下了 /// </summary> public int keyNumber; /// <summary> /// 啥时候被按下了 /// </summary> public long time; public int mouseX; public int mouseY; public string Str() { string s = "" + keyState + "," + keyNumber + "," + time + "," + mouseX + "," + mouseY; return s; } } public class RecordFileManage { string path; long startTime; List<RecordFile> list; public RecordFileManage(long startTime, string path) { list = new List<RecordFile>(); this.startTime = startTime; this.path = path; } public void AddKeyboard(Keys key, int keyState, long time) { var rf = new RecordFile(); rf.keyState = keyState; rf.keyNumber = (int)key; rf.time = time; list.Add(rf); } /// <summary> /// 添加鼠标记录 /// </summary> /// <param name="key"></param> /// <param name="keyState">keyDown =0 ,keyUp =1</param> /// <param name="time"></param> /// <param name="x"></param> /// <param name="y"></param> public void AddMouse(MouseButtons key, int keyState, long time, int x, int y) { var rf = new RecordFile(); rf.keyState = keyState; rf.keyNumber = (int)key; rf.time = time; rf.mouseX = x; rf.mouseY = y; list.Add(rf); } public void SaveFile() { //为防止错误发生,按时间戳 从小到大排列 var sortedList = list.OrderBy(row => row.time).ToList(); // 追加模式 string writePath = path; using (Stream outStream = new FileStream(writePath, FileMode.Append)) //Append:文件存在(在打开文件,流指向文件的末尾),文件不存在(创建一个新文件) using (var sw = new System.IO.StreamWriter(outStream, Encoding.UTF8)) { sw.WriteLine(startTime + ""); sortedList.ForEach(a => { sw.WriteLine(a.Str()); }); } } public static void RunFile(MyThread myThread, object[] parameters) { var filePath = (string)parameters[0]; if (string.IsNullOrEmpty(filePath) == true || System.IO.File.Exists(filePath) == false) return; var list = new List<RecordFile>(); var File = new List<string>(); using (Stream outStream = new FileStream(filePath, FileMode.Open)) //Append:文件存在(在打开文件,流指向文件的末尾),文件不存在(创建一个新文件) using (var sr = new System.IO.StreamReader(outStream, Encoding.UTF8)) { string line = ""; while ((line = sr.ReadLine()) != null) { File.Add(line); } } long startTime = long.Parse(File[0]); if (File.Count > 0) { File.RemoveAt(0); } long lastTime = 0; File.ForEach(line => { var rf = new RecordFile(); var arr = line.Split(","); int i = 0; //键盘:2,97,95,0,0 //鼠标:2,,31,1034,581 rf.keyState = int.Parse(arr[i++]); rf.keyNumber = int.Parse(arr[i++]); rf.time = long.Parse(arr[i++]); rf.mouseX = int.Parse(arr[i++]); rf.mouseY = int.Parse(arr[i++]); list.Add(rf); }); // 根据time字段进行从小到大的排序 var recordFiles = list.OrderBy(recordFile => recordFile.time).ToList(); for(int n=0;n< recordFiles.Count;n++) { if (myThread.isRunning == false) { break;//终止标志 } var rf = recordFiles[n]; var delayTime = rf.time - startTime - lastTime; lastTime = rf.time - startTime; //string a = "delay = rf.time - startTime - lastTime :" + delayTime + " = " + rf.time + "-" + startTime + "-" + lastTime; // WinformExtension.WriteLineOnDisktopCreatTxtAndOpen(a); Thread.Sleep((int)(delayTime)); if (rf.mouseX == 0) {//键盘事件 Keys key = (Keys)rf.keyNumber; if (rf.keyState == 0) { KeyboardHelper.KeyDown(key); } else { KeyboardHelper.KeyUp(key); } } else {//鼠标事件 MouseButtons key = (MouseButtons)rf.keyNumber; MouseEventFlags mfKey = MouseHelper.MouseEventFlags_To_MouseButtons(key, rf.keyState); MouseHelper.KeyDownOrUp(mfKey, rf.mouseX, rf.mouseY); } } } } public class RecordFileManage_V2 { string path; List<RecordFile> list; public RecordFileManage_V2(string path) { list = new List<RecordFile>(); this.path = path; } public void AddKeyboard(Keys key, int keyState, long time) { var rf = new RecordFile(); rf.keyState = keyState; rf.keyNumber = (int)key; rf.time = time; list.Add(rf); } /// <summary> /// 添加鼠标记录 /// </summary> /// <param name="key"></param> /// <param name="keyState">keyDown =0 ,keyUp =1</param> /// <param name="time"></param> /// <param name="x"></param> /// <param name="y"></param> public void AddMouse(MouseButtons key, int keyState, long time, int x, int y) { var rf = new RecordFile(); rf.keyState = keyState; rf.keyNumber = (int)key; rf.time = time; rf.mouseX = x; rf.mouseY = y; list.Add(rf); } public void SaveFile() { // 追加模式 string writePath = path; using (Stream outStream = new FileStream(writePath, FileMode.OpenOrCreate)) //Append:文件存在(在打开文件,流指向文件的末尾),文件不存在(创建一个新文件) using (var sw = new System.IO.StreamWriter(outStream, Encoding.UTF8)) { Form1.textBox1Static.Text.DelEmptyLines().Split("\n").ToList().ForEach(a => { sw.Write(a); }); } } static string[] mouseEvents = { "MoveTo", "LeftDown", "LeftUp" , "RightDown", "RightDown" , "MiddleDown", "MiddleUp" , }; public static void Run(MyThread myThread, object[] parameters) { string str = (string)parameters[0]; if (string.IsNullOrEmpty(str) == true) return; Dictionary<string, MouseEventFlags> mouseDic = new Dictionary<string, MouseEventFlags>(); mouseDic.Add("MoveTo", MouseEventFlags.Move); mouseDic.Add("LeftDown", MouseEventFlags.LeftDown); mouseDic.Add("LeftUp", MouseEventFlags.LeftUp); mouseDic.Add("RightDown", MouseEventFlags.RightDown); mouseDic.Add("RightUp", MouseEventFlags.RightUp); mouseDic.Add("MiddleDown", MouseEventFlags.MiddleDown); mouseDic.Add("MiddleUp", MouseEventFlags.MiddleUp); var list = new List<RecordFile>(); var File = new List<string>(); var allLine = str.Split("\r\n"); allLine.ToList().ForEach(a => { if (a.IsEmptyLine_Contontaining_Blank_Character()) { //不添加空行 } else { File.Add(a); } }); int x = 0, y = 0; for (int i = 0; i < File.Count; i++) { if (myThread.isRunning == false) { break;//终止标志 } var line = File[i]; string copyLine = string.Copy(line); string currName = "Delay "; if (copyLine.Contains(currName)) { int delayTime = int.Parse(copyLine.Del(currName)); Thread.Sleep(delayTime); continue; } bool isMouseEvent = false; string a = ""; for (int j = 0; j < mouseEvents.Length; j++) { if (line.Contains(mouseEvents[j])) { a = mouseEvents[j]; isMouseEvent = true; break; } } if (isMouseEvent == true) { isMouseEvent = line.Contains(a); //MoveTo 913, 631 if (a == "MoveTo") { string[] arr = copyLine.Del(a + " ").Split(", "); if (arr.Length == 2) { x = int.Parse(arr[0]); y = int.Parse(arr[1]); } else { throw new Exception("鼠标坐标解析失败 丢失"); } } MouseHelper.KeyDownOrUp(mouseDic[a], x, y); continue; } //解析键盘事件 //KeyDown "D2", 1 //KeyUp "D2", 1 string[] keyEvents = { "KeyDown", "KeyUp" }; if (line.Contains(keyEvents[0])) { //var t = line.Del(keyEvents[0] + " "); //var t1 = line.Del(keyEvents[0] + " ").Split(", "); //var t2 = line.Del(keyEvents[0] + " ").Split(", ")[0]; //var t3 = line.Del(keyEvents[0] + " ").Split(", ")[0].Replace("\"", ""); //var t4 = (Keys)Enum.Parse(typeof(Keys), line.Del(keyEvents[0] + " ").Split(", ")[0].Del("\"")); Keys key = (Keys)Enum.Parse(typeof(Keys), line.Del(keyEvents[0] + " ").Split(", ")[0].Del("\"")); KeyboardHelper.KeyDown(key); } if (line.Contains(keyEvents[1])) { Keys key = (Keys)Enum.Parse(typeof(Keys), line.Del(keyEvents[1] + " ").Split(", ")[0].Del("\"")); KeyboardHelper.KeyUp(key); } } } public static void RunFile(string filePath) { if (string.IsNullOrEmpty(filePath) == true || System.IO.File.Exists(filePath) == false) return; string str = ""; using (Stream outStream = new FileStream(filePath, FileMode.Open)) //Append:文件存在(在打开文件,流指向文件的末尾),文件不存在(创建一个新文件) using (var sr = new System.IO.StreamReader(outStream, Encoding.UTF8)) { str =sr.ReadToEnd(); } MyThread thread1 = new MyThread(); thread1.Bind(RecordFileManage_V2.Run, str); thread1.Start(); Form1.myThreads.Add(thread1); } } public enum KState { Null, Recording, Runing, } }
using System; using System.Windows.Forms; using MouseKeyboardActivityMonitor.WinApi; namespace MouseKeyboardActivityMonitor { /// <summary> /// This class monitors all keyboard activities and provides appropriate events. /// </summary> public class KeyboardHookListener : BaseHookListener { /// <summary> /// Initializes a new instance of <see cref="KeyboardHookListener"/>. /// </summary> /// <param name="hooker">Depending on this parameter the listener hooks either application or global keyboard events.</param> /// <remarks>Hooks are not active after instantiation. You need to use either <see cref="BaseHookListener.Enabled"/> property or call <see cref="BaseHookListener.Start"/> method.</remarks> public KeyboardHookListener(Hooker hooker) : base(hooker) { } /// <summary> /// This method processes the data from the hook and initiates event firing. /// </summary> /// <param name="wParam">The first Windows Messages parameter.</param> /// <param name="lParam">The second Windows Messages parameter.</param> /// <returns> /// True - The hook will be passed along to other applications. /// <para> /// False - The hook will not be given to other applications, effectively blocking input. /// </para> /// </returns> protected override bool ProcessCallback(int wParam, IntPtr lParam) { KeyEventArgsExt e = KeyEventArgsExt.FromRawData(wParam, lParam, IsGlobal); InvokeKeyDown(e); InvokeKeyPress(wParam, lParam); InvokeKeyUp(e); return !e.Handled; } /// <summary> /// Returns the correct hook id to be used for <see cref="Hooker.SetWindowsHookEx"/> call. /// </summary> /// <returns>WH_KEYBOARD (0x02) or WH_KEYBOARD_LL (0x13) constant.</returns> protected override int GetHookId() { return IsGlobal ? GlobalHooker.WH_KEYBOARD_LL : AppHooker.WH_KEYBOARD; } /// <summary> /// Occurs when a key is preseed. /// </summary> public event KeyEventHandler KeyDown; private void InvokeKeyDown(KeyEventArgsExt e) { KeyEventHandler handler = KeyDown; if (handler == null || e.Handled || !e.IsKeyDown) { return; } handler(this, e); } /// <summary> /// Occurs when a key is pressed. /// </summary> /// <remarks> /// Key events occur in the following order: /// <list type="number"> /// <item>KeyDown</item> /// <item>KeyPress</item> /// <item>KeyUp</item> /// </list> ///The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events. ///Use the KeyChar property to sample keystrokes at run time and to consume or modify a subset of common keystrokes. ///To handle keyboard events only in your application and not enable other applications to receive keyboard events, ///set the <see cref="KeyPressEventArgs.Handled"/> property in your form's KeyPress event-handling method to <b>true</b>. /// </remarks> public event KeyPressEventHandler KeyPress; private void InvokeKeyPress(int wParam, IntPtr lParam) { InvokeKeyPress(KeyPressEventArgsExt.FromRawData(wParam, lParam, IsGlobal)); } private void InvokeKeyPress(KeyPressEventArgsExt e) { KeyPressEventHandler handler = KeyPress; if (handler == null || e.Handled || e.IsNonChar) { return; } handler(this, e); } /// <summary> /// Occurs when a key is released. /// </summary> public event KeyEventHandler KeyUp; private void InvokeKeyUp(KeyEventArgsExt e) { KeyEventHandler handler = KeyUp; if (handler == null || e.Handled || !e.IsKeyUp) { return; } handler(this, e); } /// <summary> /// Release delegates, unsubscribes from hooks. /// </summary> /// <filterpriority>2</filterpriority> public override void Dispose() { KeyPress = null; KeyDown = null; KeyUp = null; base.Dispose(); } } }
using System; using System.Windows.Forms; using MouseKeyboardActivityMonitor.WinApi; namespace MouseKeyboardActivityMonitor { /// <summary> /// This class monitors all mouse activities and provides appropriate events. /// </summary> public class MouseHookListener : BaseHookListener { private Point m_PreviousPosition; private int m_PreviousClickedTime; private MouseButtons m_PreviousClicked; private MouseButtons m_DownButtonsWaitingForMouseUp; private MouseButtons m_SuppressButtonUpFlags; private int m_SystemDoubleClickTime; /// <summary> /// Initializes a new instance of <see cref="MouseHookListener"/>. /// </summary> /// <param name="hooker">Depending on this parameter the listener hooks either application or global mouse events.</param> /// <remarks> /// Hooks are not active after installation. You need to use either <see cref="BaseHookListener.Enabled"/> property or call <see cref="BaseHookListener.Start"/> method. /// </remarks> public MouseHookListener(Hooker hooker) : base(hooker) { m_PreviousPosition = new Point(-1, -1); m_PreviousClickedTime = 0; m_DownButtonsWaitingForMouseUp = MouseButtons.None; m_SuppressButtonUpFlags = MouseButtons.None; m_PreviousClicked = MouseButtons.None; m_SystemDoubleClickTime = Mouse.GetDoubleClickTime(); } //################################################################## #region ProcessCallback and related subroutines /// <summary> /// This method processes the data from the hook and initiates event firing. /// </summary> /// <param name="wParam">The first Windows Messages parameter.</param> /// <param name="lParam">The second Windows Messages parameter.</param> /// <returns> /// True - The hook will be passed along to other applications. /// <para> /// False - The hook will not be given to other applications, effectively blocking input. /// </para> /// </returns> protected override bool ProcessCallback(int wParam, IntPtr lParam) { MouseEventExtArgs e = MouseEventExtArgs.FromRawData(wParam, lParam, IsGlobal); if (e.IsMouseKeyDown) { ProcessMouseDown(ref e); } if (e.Clicks == 1 && e.IsMouseKeyUp && !e.Handled) { ProcessMouseClick(ref e); } if (e.Clicks == 2 && !e.Handled) { InvokeMouseEventHandler(MouseDoubleClick, e); } if (e.IsMouseKeyUp) { ProcessMouseUp(ref e); } if (e.WheelScrolled) { InvokeMouseEventHandler(MouseWheel, e); } if (HasMoved(e.Point)) { ProcessMouseMove(ref e); } return !e.Handled; } private void ProcessMouseDown(ref MouseEventExtArgs e) { if (IsGlobal) { ProcessPossibleDoubleClick(ref e); } else { // These are only used for global. No need for them in AppHooks m_DownButtonsWaitingForMouseUp = MouseButtons.None; m_PreviousClicked = MouseButtons.None; m_PreviousClickedTime = 0; } InvokeMouseEventHandler(MouseDown, e); InvokeMouseEventHandlerExt(MouseDownExt, e); if (e.Handled) { SetSupressButtonUpFlag(e.Button); e.Handled = true; } } private void ProcessPossibleDoubleClick(ref MouseEventExtArgs e) { if (IsDoubleClick(e.Button, e.Timestamp)) { e = e.ToDoubleClickEventArgs(); m_DownButtonsWaitingForMouseUp = MouseButtons.None; m_PreviousClicked = MouseButtons.None; m_PreviousClickedTime = 0; } else { m_DownButtonsWaitingForMouseUp |= e.Button; m_PreviousClickedTime = e.Timestamp; } } private void ProcessMouseClick(ref MouseEventExtArgs e) { if ((m_DownButtonsWaitingForMouseUp & e.Button) != MouseButtons.None) { m_PreviousClicked = e.Button; m_DownButtonsWaitingForMouseUp = MouseButtons.None; InvokeMouseEventHandler(MouseClick, e); InvokeMouseEventHandlerExt(MouseClickExt, e); } } private void ProcessMouseUp(ref MouseEventExtArgs e) { if (!HasSupressButtonUpFlag(e.Button)) { InvokeMouseEventHandler(MouseUp, e); } else { RemoveSupressButtonUpFlag(e.Button); e.Handled = true; } } private void ProcessMouseMove(ref MouseEventExtArgs e) { m_PreviousPosition = e.Point; InvokeMouseEventHandler(MouseMove, e); InvokeMouseEventHandlerExt(MouseMoveExt, e); } #endregion private void RemoveSupressButtonUpFlag(MouseButtons button) { m_SuppressButtonUpFlags = m_SuppressButtonUpFlags ^ button; } private bool HasSupressButtonUpFlag(MouseButtons button) { return (m_SuppressButtonUpFlags & button) != 0; } private void SetSupressButtonUpFlag(MouseButtons button) { m_SuppressButtonUpFlags = m_SuppressButtonUpFlags | button; } /// <summary> /// Returns the correct hook id to be used for <see cref="Hooker.SetWindowsHookEx"/> call. /// </summary> /// <returns>WH_MOUSE (0x07) or WH_MOUSE_LL (0x14) constant.</returns> protected override int GetHookId() { return IsGlobal ? GlobalHooker.WH_MOUSE_LL : AppHooker.WH_MOUSE; } private bool HasMoved(Point actualPoint) { return m_PreviousPosition != actualPoint; } private bool IsDoubleClick(MouseButtons button, int timestamp) { return button == m_PreviousClicked && timestamp - m_PreviousClickedTime <= m_SystemDoubleClickTime; // Mouse.GetDoubleClickTime(); } private void InvokeMouseEventHandler(MouseEventHandler handler, MouseEventArgs e) { if (handler != null) { handler(this, e); } } private void InvokeMouseEventHandlerExt(EventHandler<MouseEventExtArgs> handler, MouseEventExtArgs e) { if (handler != null) { handler(this, e); } } /// <summary> /// Occurs when the mouse pointer is moved. /// </summary> public event MouseEventHandler MouseMove; /// <summary> /// Occurs when the mouse pointer is moved. /// </summary> /// <remarks> /// This event provides extended arguments of type <see cref = "MouseEventArgs" /> enabling you to /// supress further processing of mouse movement in other applications. /// </remarks> public event EventHandler<MouseEventExtArgs> MouseMoveExt; /// <summary> /// Occurs when a click was performed by the mouse. /// </summary> public event MouseEventHandler MouseClick; /// <summary> /// Occurs when a click was performed by the mouse. /// </summary> /// <remarks> /// This event provides extended arguments of type <see cref = "MouseEventArgs" /> enabling you to /// supress further processing of mouse click in other applications. /// </remarks> [Obsolete("To supress mouse clicks use MouseDownExt event instead.")] public event EventHandler<MouseEventExtArgs> MouseClickExt; /// <summary> /// Occurs when the mouse a mouse button is pressed. /// </summary> public event MouseEventHandler MouseDown; /// <summary> /// Occurs when the mouse a mouse button is pressed. /// </summary> /// <remarks> /// This event provides extended arguments of type <see cref = "MouseEventArgs" /> enabling you to /// supress further processing of mouse click in other applications. /// </remarks> public event EventHandler<MouseEventExtArgs> MouseDownExt; /// <summary> /// Occurs when a mouse button is released. /// </summary> public event MouseEventHandler MouseUp; /// <summary> /// Occurs when the mouse wheel moves. /// </summary> public event MouseEventHandler MouseWheel; /// <summary> /// Occurs when a mouse button is double-clicked. /// </summary> public event MouseEventHandler MouseDoubleClick; /// <summary> /// Release delegates, unsubscribes from hooks. /// </summary> /// <filterpriority>2</filterpriority> public override void Dispose() { MouseClick = null; MouseClickExt = null; MouseDown = null; MouseDownExt = null; MouseMove = null; MouseMoveExt = null; MouseUp = null; MouseWheel = null; MouseDoubleClick = null; base.Dispose(); } } }
今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
上一篇
已是最后文章
下一篇
已是最新文章