C#在任何地方检测ESC按键

时间:2014-09-07 17:03:18

标签: c# keyboard

我有一个C#窗口应用程序正在运行,我想在任何地方按ESC时关闭它,即使我的应用程序没有焦点。我该如何实现呢?

我找到了一些低级控制键盘,我不知道也不明白。

3 个答案:

答案 0 :(得分:4)

使用此课程:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace myNameSpace
{
    class InterceptKeys
    {
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private const int WM_ALTDOWN = 0x0104;
        private static LowLevelKeyboardProc _proc = HookCallback;
        private static IntPtr _hookID = IntPtr.Zero;

        public static void Start()
        {
            _hookID = SetHook(_proc);
        }

        public static void Stop()
        {
            UnhookWindowsHookEx(_hookID);
        }

        public static event KeyEventHandler OnKeyDown;

        private static IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                    GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private delegate IntPtr LowLevelKeyboardProc(
            int nCode, IntPtr wParam, IntPtr lParam);

        private static IntPtr HookCallback(
            int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_ALTDOWN))
            {
                var vkCode = (Keys)Marshal.ReadInt32(lParam);
                OnKeyDown(null, new KeyEventArgs(vkCode));
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
    }
}

这样:

myNameSpace.InterceptKeys.OnKeyDown+= new KeyEventHandler(myKeyDown);

myNameSpace.InterceptKeys.Start();

onKeyDown可以是这样的:

void myKeyDown(object sender, KeyEventArgs e)
{
    // Some code for closing you form
    // or any thing you need after press Esc
    // with e.KeyCode
};

答案 1 :(得分:0)

答案 2 :(得分:0)

对于那些寻求完整解决方案来检测全局按键并进行按键操作的人,我已经把它全部弄清楚了,并将代码放入pastebin.com中,从来没有"被删除。请特别注意InterceptKeys.cs(执行Ctrl + F):

http://pastebin.com/u7FUhgYr

^此代码已完成,但它不是最佳的。

然后我改进了一些代码(一个改变是我创建的新SendKeys函数,它发送你想要的任何键按下/发布 - 更容易使用!)。这堂课,MakroKeys:

http://pastebin.com/Dedx6hRw

有两个静态函数可用于将字符串转换为System.Windows.Forms.Keys,反之亦然(如果您希望用户能够通过文本和/或显示输入自己的密钥,这将非常有用当前按下的键通过文本);这有改进的MainForm.cs代码(包含SendKeys函数):

http://pastebin.com/BXzmWeMK

(注意MakroKeys.GetKey(" lcontrolkey")调用,它演示了该功能的用法。)

结合所有这些,你可以做一些非常棒的事情。另请注意,因为这是导入DLL并调用Windows API函数,所以您可以在以下方法中轻松地执行此操作。也是c ++。世界,你是受欢迎的。 ;)