【问题标题】:How to detect "outer" key presses in C#?如何检测 C# 中的“外部”按键?
【发布时间】:2013-09-22 18:02:16
【问题描述】:

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

感谢您的帮助!

【问题讨论】:

  • 您可能需要一些global keyboard hook 解决方案。
  • @KingKing 谢谢。但我不知道(谷歌搜索后)如何做到这一点。
  • 实际上你的代码每次按下X都有效,按下auto clicks后会随机完成,那么你的Form可能是不活动的。因此,您可以尝试将其置于前面,等待用户按下另一个 X

标签: c# windows winforms mouse mouseevent


【解决方案1】:

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

另外,这里有一个代码示例:https://gist.github.com/Ciantic/471698

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

【讨论】:

    猜你喜欢
    • 2011-07-16
    • 2011-02-26
    • 2019-11-22
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 2013-12-14
    相关资源
    最近更新 更多