如何在C#中检测“外部”按键?

时间:2013-09-22 09:31:30

标签: c# windows winforms mouse mouseevent

我正在使用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?当窗口关闭时,还是任何其他按键?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

请查看以下文章:Low-Level Keyboard Hook in C#

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

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