使用C#的快捷键

Bry*_*yan 6 c# keyboard-shortcuts

我想创建一个具有发送键的简单应用程序(如快捷键).情况是,只要创建的应用程序处于非活动状态窗口,只要系统正在运行,系统仍会识别用户按下的键.

简而言之,只需按下(窗口+ D)即可在您使用的应用程序/窗口中立即显示您的桌面.

任何人都可以帮助我如何在C#2005中做到这一点

tof*_*tim 5

使用以下内容:

[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
Run Code Online (Sandbox Code Playgroud)

和

[Flags]
public enum ModifierKeys : uint
{
    Alt = 1,
    Control = 2,
    Shift = 4,
    Win = 8
}

private ModifierKeys _getModifierKeys(bool isAlt, bool isCtrl, bool isShift, bool isWin)
{
    return (isAlt ? ModifierKeys.Alt : 0) |
            (isCtrl ? ModifierKeys.Control : 0) |
            (isShift ? ModifierKeys.Shift : 0) |
            (isWin ? ModifierKeys.Win : 0);
}
Run Code Online (Sandbox Code Playgroud)

然后,注册你的热键,

RegisterHotKey(hWndNotify, id,
                    (uint)_getModifierKeys(_isAlt, _isCtrl, _isShift, _isWin),
                    (uint)_key);
Run Code Online (Sandbox Code Playgroud)

在主机hWnd中,监听WM_HOTKEYREADY,然后使用检查热键匹配

public bool Matches(ref Message m)
{
    Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
    ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);

    if ((key == Key) &&
        (modifier == Modifier))
    {
        return true;
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)