注册一个已经被使用的热键 [英] Register hot key that is already used

查看:272
本文介绍了注册一个已经被使用的热键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:

我要听热键序列(按Ctrl + Alt +左​​)全球范围内,所以我使用:

I want to listen to a hot key sequence (Ctrl+Alt+Left) globally, so I'm using:

[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

这伟大工程与许多其他热键序列,如按Ctrl + Alt + PageUp键按Ctrl + Alt + PageDown键,等...但随着出现问题按Ctrl + Alt +左​​,具体

This works great with many other hot key sequences, such as Ctrl+Alt+PageUp, Ctrl+Alt+PageDown, etc... But a problem occurs with Ctrl+Alt+Left, specifically.

问题:

在一台计算机上,它工作得很好,就像任何其他热键序列,但不同的计算机上,其中按Ctrl + Alt +箭头 。使用旋转屏幕,它无法注册热键(即返回零,并没有得到回调窗口的句柄)

On one computer, it works just fine, like any other hot key sequence, but on a different computer, where Ctrl+Alt+Arrow is used to rotate the screen, it fails to register the hot key (i.e returns zero and doesn't get callbacks to the window's handle).

MSDN说:如果热键指定的按键已经被另一个热键注册RegisterHotKey失败。

我想是能够注册的热键序列无论什么时候,如果需要,将其覆盖。我当然希望在屏幕上保持不旋转,只要我的程序正在运行,至少。

I would like to be able to register that hot key sequence no matter what, and if needed, override it. I would certainly want the screen to remain unrotated, at least for as long as my program is running.

更改热键序列是不是一个真正的选择,因为其他计算机。可能有可能导致故障以及其他热键序列

Changing the hotkey sequence isn't really an option, since other computers might have other hotkey sequences that may cause failure as well.

问题:

之间有什么区别按Ctrl + Alt +左​​作为屏幕旋转的热键和一个控制+ S 作为一种节省热键,原因之一失败,而不是其他? (不知是不是因为一个是全局热键,第二个是上下文?)

What is the difference between Ctrl+Alt+Left as a screen-rotating hotkey and a Ctrl+S as a saving hotkey, the causes one to fail but not the other? (maybe it is because one is a global hotkey and the second is contextual?)

是否有可能重写热键完全?这是一个好主意吗?

Is it possible to override hotkeys entirely? Is that a good idea?

更重要的是,我怎么能保证我的热键将被注册?

Most importantly, how can I assure that my hotkey will be registered?

推荐答案

我只是改变了我的方法从热键来挂钩。
我在听任何低级别的键盘新闻发布会,并使用WINAPI这样即使火灾时,得到修饰状态。然后,我对目前按顺序全部信息。

I've just changed my approach from hotkeys to hooks. I'm listening to any low-level keyboard press event, and getting the modifiers' states when such even fires using winAPI. Then I have full information about currently pressed sequence.

这是很长的和丑陋的代码做这一切,但最终很容易的工作。

It's very long and ugly code to do all that, but eventually it is easy to work with.

/// <summary>
/// A class that manages a global low level keyboard hook
/// </summary>
class GlobalKeyboardHook
{
    #region Constant, Structure and Delegate Definitions

    /// <summary>
    /// defines the callback type for the hook
    /// </summary>
    public delegate int KeyboardHookProc(int code, int wParam, ref KeyboardHookStruct lParam);

    public struct KeyboardHookStruct
    {
        public int vkCode;
        public int scanCode;
        public int flags;
        public int time;
        public int dwExtraInfo;
    }

    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x100;
    private const int WM_KEYUP = 0x101;
    private const int WM_SYSKEYDOWN = 0x104;
    private const int WM_SYSKEYUP = 0x105;

    #endregion

    /// <summary>
    /// The collections of keys to watch for
    /// </summary>
    public List<Keys> HookedKeys = new List<Keys>();

    /// <summary>
    /// Handle to the hook, need this to unhook and call the next hook
    /// </summary>
    private IntPtr _hhook = IntPtr.Zero;

    /// <summary>
    /// Initializes a new instance of the <see cref="GlobalKeyboardHook"/> class and installs the keyboard hook.
    /// </summary>
    public GlobalKeyboardHook()
    {
        this.Hook();
    }

    /// <summary>
    /// Releases unmanaged resources and performs other cleanup operations before the
    /// <see cref="GlobalKeyboardHook"/> is reclaimed by garbage collection and uninstalls the keyboard hook.
    /// </summary>
    ~GlobalKeyboardHook()
    {
        this.Unhook();
    }

    /// <summary>
    /// Installs the global hook
    /// </summary>
    public void Hook()
    {
        IntPtr hInstance = LoadLibrary("User32");
        this._hhook = SetWindowsHookEx(WH_KEYBOARD_LL, this.HookProc, hInstance, 0);
    }

    /// <summary>
    /// Uninstalls the global hook
    /// </summary>
    public void Unhook()
    {
        UnhookWindowsHookEx(this._hhook);
    }

    /// <summary>
    /// The callback for the keyboard hook
    /// </summary>
    /// <param name="code">The hook code, if it isn't >= 0, the function shouldn't do anyting</param>
    /// <param name="wParam">The event type</param>
    /// <param name="lParam">The keyhook event information</param>
    /// <returns></returns>
    private int HookProc(int code, int wParam, ref KeyboardHookStruct lParam)
    {
        if (code >= 0)
        {
            var key = (Keys) lParam.vkCode;

            if (this.HookedKeys.Contains(key))
            {
                var handler = this.KeyPressed;

                if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (handler != null))
                {
                    ModifierKeys mods = 0;

                    if (Keyboard.IsKeyDown(Keys.Control) || Keyboard.IsKeyDown(Keys.ControlKey) ||
                        Keyboard.IsKeyDown(Keys.LControlKey) || Keyboard.IsKeyDown(Keys.RControlKey))
                    {
                        mods |= ModifierKeys.Control;
                    }

                    if (Keyboard.IsKeyDown(Keys.Shift) || Keyboard.IsKeyDown(Keys.ShiftKey) ||
                        Keyboard.IsKeyDown(Keys.LShiftKey) || Keyboard.IsKeyDown(Keys.RShiftKey))
                    {
                        mods |= ModifierKeys.Shift;
                    }

                    if (Keyboard.IsKeyDown(Keys.LWin) || Keyboard.IsKeyDown(Keys.RWin))
                    {
                        mods |= ModifierKeys.Win;
                    }

                    if (Keyboard.IsKeyDown(Keys.Alt))
                    {
                        mods |= ModifierKeys.Alt;
                    }

                    handler(this, new KeyPressedEventArgs(mods, key));
                }
            }
        }

        return CallNextHookEx(this._hhook, code, wParam, ref lParam);
    }

    public event EventHandler<KeyPressedEventArgs> KeyPressed;

    #region DLL imports

    /// <summary>
    /// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null
    /// </summary>
    /// <param name="idHook">The id of the event you want to hook</param>
    /// <param name="callback">The callback.</param>
    /// <param name="hInstance">The handle you want to attach the event to, can be null</param>
    /// <param name="threadId">The thread you want to attach the event to, can be null</param>
    /// <returns>a handle to the desired hook</returns>
    [DllImport("user32.dll")]
    private static extern IntPtr SetWindowsHookEx(int idHook, KeyboardHookProc callback, IntPtr hInstance, uint threadId);

    /// <summary>
    /// Unhooks the windows hook.
    /// </summary>
    /// <param name="hInstance">The hook handle that was returned from SetWindowsHookEx</param>
    /// <returns>True if successful, false otherwise</returns>
    [DllImport("user32.dll")]
    private static extern bool UnhookWindowsHookEx(IntPtr hInstance);

    /// <summary>
    /// Calls the next hook.
    /// </summary>
    /// <param name="idHook">The hook id</param>
    /// <param name="nCode">The hook code</param>
    /// <param name="wParam">The wparam.</param>
    /// <param name="lParam">The lparam.</param>
    /// <returns></returns>
    [DllImport("user32.dll")]
    private static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref KeyboardHookStruct lParam);

    /// <summary>
    /// Loads the library.
    /// </summary>
    /// <param name="lpFileName">Name of the library</param>
    /// <returns>A handle to the library</returns>
    [DllImport("kernel32.dll")]
    private static extern IntPtr LoadLibrary(string lpFileName);

    #endregion
}

static class Keyboard
{
    [Flags]
    private enum KeyStates
    {
        None = 0,
        Down = 1,
        Toggled = 2
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    private static extern short GetKeyState(int keyCode);

    private static KeyStates GetKeyState(Keys key)
    {
        KeyStates state = KeyStates.None;

        short retVal = GetKeyState((int)key);

        //If the high-order bit is 1, the key is down
        //otherwise, it is up.
        if ((retVal & 0x8000) == 0x8000)
            state |= KeyStates.Down;

        //If the low-order bit is 1, the key is toggled.
        if ((retVal & 1) == 1)
            state |= KeyStates.Toggled;

        return state;
    }

    public static bool IsKeyDown(Keys key)
    {
        return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
    }

    public static bool IsKeyToggled(Keys key)
    {
        return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
    }
}

/// <summary>
/// Event Args for the event that is fired after the hot key has been pressed.
/// </summary>
class KeyPressedEventArgs : EventArgs
{
    internal KeyPressedEventArgs(ModifierKeys modifier, Keys key)
    {
        this.Modifier = modifier;
        this.Key = key;

        this.Ctrl = (modifier & ModifierKeys.Control) != 0;
        this.Shift = (modifier & ModifierKeys.Shift) != 0;
        this.Win = (modifier & ModifierKeys.Win) != 0;
        this.Alt = (modifier & ModifierKeys.Alt) != 0;
    }

    public ModifierKeys Modifier { get; private set; }
    public Keys Key { get; private set; }
    public readonly bool Ctrl;
    public readonly bool Shift;
    public readonly bool Win;
    public readonly bool Alt;
}

/// <summary>
/// The enumeration of possible modifiers.
/// </summary>
[Flags]
public enum ModifierKeys : uint
{
    Alt = 1,
    Control = 2,
    Shift = 4,
    Win = 8
}

这篇关于注册一个已经被使用的热键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆