C#如何将键盘快捷键侦听器添加到App或AddIn?

时间:2014-05-18 02:42:28

标签: c# keyboard

如何绑定C#将侦听的键盘事件?以下代码应适用于任何Office AddIn或C#桌面应用程序。要使其正常工作,您应该在应用的加载功能中调用Hotkeys.Setup()。

应用程序本地的键盘事件与全局键盘事件之间是否存在差异?

如何扩展代码以测量键盘按下的持续时间?

如何扩展代码以使其在任何窗口中都能正常工作?

当前代码:

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

    namespace MyApp{
    public class Hotkeys{
    private delegate int LowLevelKeyboardProc(bool pressEnd, int keyData, Int64 keyState);
    private static IntPtr hookID;


    //Hotkeys.Setup() inside your app's loading function to initialize this class
    //return 0 to continue events registered to that keyboard shortcut, return 1 to stop            
    private static int HookCallback(bool pressEnd, int keyData, Int64 keyState)
    {
        if (pressEnd || keyState > Math.Pow(2,30))
            return 0;

        String key = ((Keys)keyData).ToString();
        if (GetKeyState((int)Keys.RShiftKey)<0 || GetKeyState((int)Keys.LShiftKey)<0)
            key += ", Shift";
        if (GetKeyState((int)Keys.ControlKey)<0)
            key += ", Control";
        if (GetKeyState((int)Keys.Menu)<0)
            key += ", Alt";

        switch (key) { 
        case "F1":
            MessageBox.Show("F1 pressed, continue events -- help window should popup");
            return 0;

        break; case "F2, Control":
            MessageBox.Show("Control F2 pressed, stop events");
            return 1;

        break; case "S, Control":
            MessageBox.Show("Control S pressed, stop events -- disabling save function");
            return 1;
        break;
        }

        return 0;
    }

    public static void Setup()
    {
        hookID = SetWindowsHookEx(2, HookCallback, IntPtr.Zero, (uint)Process.GetCurrentProcess().Threads[0].Id);
    }

    public static void Dispose()
    {
        UnhookWindowsHookEx(hookID);
    }

[DllImport("user32.dll")]
private static extern short GetKeyState(int keyId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int kid, LowLevelKeyboardProc llkp, IntPtr h, uint processId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hookid);
    }
    }

1 个答案:

答案 0 :(得分:0)

您可以为WindowsForms覆盖ProcessCmdKey:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    switch (keyData)
    {
        case Keys.F1:
            break;

        case Keys.F2:
            break;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}
相关问题