0

我正在使用 Microsoft Visual Studio 在 C# 中制作一个简单的应用程序。

应用程序使光标移动到一个点(窗体窗口外)并单击多次。我通过按 X 开始单击循环。因此,如果您有兴趣,代码如下所示:

public void Wait(int milliseconds)
        {
            System.Threading.Thread.Sleep(milliseconds);
        }

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

        public const int MOUSEEVENTF_LEFTDOWN = 0x02;
        public const int MOUSEEVENTF_LEFTUP = 0x04;
        public const int MOUSEEVENTF_RIGHTDOWN = 0x08;
        public const int MOUSEEVENTF_RIGHTUP = 0x10;

        public void MouseClick(Point pos, int click = 0)
        {
            int x = pos.X;
            int y = pos.Y;
            //MessageBox.Show("clicking mouse on " + pos.ToString());

            if (click == 1)
            {
                mouse_event(MOUSEEVENTF_RIGHTDOWN, x, y, 0, 0);
                mouse_event(MOUSEEVENTF_RIGHTUP, x, y, 0, 0);
            }
            else
            {
                mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
                mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
            }
        }

        public void MouseMove(int x, int y)
        {
            MouseMove(new Point(x,y));
        }

        public void MouseMove(Point target)
        {
            Cursor.Position = target;
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.A)
            {
                MessageBox.Show(Cursor.Position.ToString());
            }
            MouseMove(42, 42);

            if (e.KeyCode == Keys.X)
            {
                MessageBox.Show(Cursor.Position.ToString());            
                Wait(42);
                Random r = new Random();
                for (int i = 0; i < number_of_times ; i++)
                {
                    Wait(r.Next(42));
                    MouseClick(Cursor.Position);
                }

            }

        }

但是,如您所见,一旦单击开始,表单就会返回(在屏幕中不可见),因此它无法检测到按键。那么我怎样才能停止点击循环呢?如果我按Ctrl + Alt + Del,它会暂停,然后我打开任务管理器,但点击继续。

也许一种检测 ctrl alt del 的方法?或任何其他按键,当窗口关闭时?

谢谢你的帮助 !

4

1 回答 1

1

请看以下文章:C# 中的低级键盘挂钩

此外,这是一个代码示例:https ://gist.github.com/Ciantic/471698 。

全局热键可能是一个很好的解决方案: http: //bloggablea.wordpress.com/2007/05/01/global-hotkeys-with-net/

于 2013-09-22T10:02:16.017 回答