参考文章:https://blog.csdn.net/water_0815/article/details/54959062
在此基础上增加了窗口后台运行的功能,解决了自己的强迫症.
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Timers; namespace MouseMoveTimer { class Program { [DllImport("User32.dll", EntryPoint = "ShowWindow")] private static extern bool ShowWindow(IntPtr hWnd, int type); [DllImport("User32.dll", EntryPoint = "FindWindow")] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("User32.dll", EntryPoint = "mouse_event")] private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); private const int MOUSEEVENTF_MOVE = 0x0001; static void Main(string[] args) { // 1. 输入鼠标定时移动的时间间隔(秒) Console.WriteLine("Input the Timer Interval by second: "); string timerInterval = Console.ReadLine(); // 2. 定义定时器 int TimerInterval; if (Int32.TryParse(timerInterval, out TimerInterval)) { Timer timer = new System.Timers.Timer(); // 定义定时器 timer.Enabled = true; // 启用定时器 timer.Interval = 1000 * TimerInterval; // 设定时间间隔(毫秒:1秒 = 1000毫秒) timer.Elapsed += new ElapsedEventHandler(MoveMouseHandler); // 等到间隔时间到,执行 } else { Console.WriteLine("Error: Please input a number!"); } // 2.Plus 添加后台运行功能 Console.Title = "MyConsole"; IntPtr ParenthWnd = new IntPtr(0); ParenthWnd = FindWindow(null, "MyConsole"); ShowWindow(ParenthWnd, 0);//隐藏本dos窗体, 0: 后台执行;1:正常启动;2:最小化到任务栏;3:最大化 // 3. 保持程序不退出 Console.ReadKey(); } private static void ShowWindow(object parenthWnd, int v) { throw new NotImplementedException(); } /// <summary> /// 定时器方法体 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected static void MoveMouseHandler(object sender, System.Timers.ElapsedEventArgs e) { // 将鼠标移动一个像素 mouse_event(MOUSEEVENTF_MOVE, 1, 1, 0, 0); } } }