在表格不可见的情况下捕捉键盘上的任何脂肪?

时间:2015-01-04 14:34:04

标签: c# linq

我试图抓住A ... Z中的任何角色,但我没有得到它 我使用全局热键,但他们只是操纵 F2 ...... .. F12 有些像 我怎么能这样做? 我试过了:

 public Form1()
    {
        InitializeComponent();
        // register the event that is fired after the key press.
        hook.KeyPressed +=
        new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);
        // register the control + alt + F12 combination as hot key.
        hook.RegisterHotKey(GlobalHotKeys.ModifierKeys.Control | GlobalHotKeys.ModifierKeys.Alt, Keys.F12);
        hook.RegisterHotKey(GlobalHotKeys.ModifierKeys.Control | GlobalHotKeys.ModifierKeys.Alt, Keys.F2);

    }
    void hook_KeyPressed(object sender, KeyPressedEventArgs e)
    {
        // show the keys pressed in a label.
        MessageBox.Show(e.Key.ToString());

    }

1 个答案:

答案 0 :(得分:2)

我相信你应该使用Global Keyboard Hook来捕获非活动或隐藏形式的关键事件,你可以使用Keyboard Hooks Library来简化这个过程,这里有一个基于提到的库的示例:

using System.Windows.Forms;
using MouseKeyboardActivityMonitor.WinApi;

namespace Demo
{
    public partial class MainForm : Form
    {
        private readonly KeyboardHookListener hook=new KeyboardHookListener(new GlobalHooker());

        public MainForm()
        {
            InitializeComponent();

            hook.KeyDown += hook_KeyDown;
            hook.Enabled = true;
        }

        void hook_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Control && e.Alt && e.KeyCode==Keys.F12)
                MessageBox.Show(@"Alt+Ctrl+F12 Pressed.");
        }
    }
}

控制台示例:

注意:添加System.Windows.Forms.dll作为控制台应用程序的参考

using System;
using System.Threading;
using System.Windows.Forms;
using MouseKeyboardActivityMonitor.WinApi;

namespace Demo
{
    internal class KeyboardHook : IDisposable
    {
        private readonly KeyboardHookListener _hook = new KeyboardHookListener(new     GlobalHooker());

        public KeyboardHook()
        {
            _hook.KeyDown += hook_KeyDown;
            _hook.Enabled = true;
        }

        private void hook_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.Alt && e.KeyCode == Keys.F12)
                MessageBox.Show(@"Alt+Ctrl+F12 Pressed.");

        }

        public void Dispose()
        {
            _hook.Enabled = false;
            _hook.Dispose();
        }
    }

    internal static class Program
    {
        private static void Main()
        {
            var t = new Thread(() =>
            {
                using (new KeyboardHook())
                    Application.Run();
            });

            t.Start();

            Console.WriteLine(@"press 'C' key to exit application...");
            while (Console.ReadKey().Key != ConsoleKey.C){}

            Application.Exit();
        }
    }
}