C#检测所有窗口中的按键事件

标签 c# .net windows focus keyevent

嘿,我的键事件处理程序有问题。这是来源:

using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Data;
        using System.Drawing;
        using System.Linq;
        using System.Text;
        using System.Windows.Forms;
        using System.Diagnostics;
        using System.Threading;

        namespace WindowsFormsApplication3
        {
            public partial class Form1 : Form
            {
                public Form1()
                {
                    InitializeComponent();
                }

                [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 Form1_KeyPessed(object sender, KeyEventArgs e)
                {
                    if (e.KeyCode == Keys.F2)
                    {
                        DrawSquare();
                    }
                }

                public void DrawSquare()
                {
                    int line = Convert.ToInt16(textBox1.Text);
                    int time = Convert.ToInt16(textBox2.Text);

                    int x = MousePosition.X;
                    int y = MousePosition.Y;
                    Cursor.Position = new Point(x - line / 2, y - line / 2);
                    mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
                    Thread.Sleep(time);
                    Cursor.Position = new Point(x - line / 2, y + line / 2);
                    Thread.Sleep(time);
                    Cursor.Position = new Point(x - line / 2, y + line / 2);
                    Thread.Sleep(time);
                    Cursor.Position = new Point(x + line / 2, y - line / 2);
                    Thread.Sleep(time);
                    Cursor.Position = new Point(x - line / 2, y - line / 2);
                    mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
                    Thread.Sleep(time);
                    Cursor.Position = new Point(x, y);
                }
            }      
        }

现在,当我在窗体中按 F2 时它只会绘制正方形,但我希望它适用于所有窗口。 我还需要什么? (这是一种完美形状的自动抽屉)

最佳答案

如果你只想处理几个组合键,你可以使用 RegisterHotKey .如果您想检测所有不同的按键事件,请使用 the global hook as Paul suggested .

关于C#检测所有窗口中的按键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5450362/

相关文章:

.net - 插值字符串 $ 被视为无效字符并返回错误 BC30037 (vb.net)

windows - 如何衡量远程桌面性能?

java - 如何显式关闭内存缓存中的连接

c# - Linq to Twitter - token 无效/过期

c# - 打印机通信捕获

.net - 如果我的最终目标是 ASP.NET MVC,我应该学习多少 ASP.NET?

c# - 如何让 Debug.WriteLine 与其他进程一起工作?

c# - 获取表的 SQL Server 架构

c# - 如果我替换 PictureBox 控件中的图像,我应该先处理原始图像吗?

C# 输入验证检查正数