如何检测WPF中的修饰键状态?

时间:2011-04-21 23:05:16

标签: c# .net wpf keyboard

是否有一些全局构造可以在我需要访问时使用,无论Control,Shift,Alt按钮是否已关闭?例如MouseDown内的TreeView事件。

如果是这样的话?

6 个答案:

答案 0 :(得分:215)

使用班级Keyboard。使用Keyboard.IsKeyDown,您可以检查Control,Shift,Alt现在是否已关闭。

换班次:

if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
{ /* Your code */ }

对于控制:

if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{ /* Your code */ }

对于Alt:

if (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt))
{ /* Your code */ }

答案 1 :(得分:110)

还有:

// Have to get this value before opening a dialog, or user will have released the control key
if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{

}

答案 2 :(得分:7)

    private bool IsShiftKey { get; set; }

    private void OnPreviewKeyDown(object sender, KeyEventArgs e)
    {
        IsShiftKey = Keyboard.Modifiers == ModifierKeys.Shift ? true : false;

        if ((Key.Oem3 == e.Key || ((IsShiftKey && Key.Oem4 == e.Key) || (IsShiftKey && Key.Oem6 == e.Key) || (IsShiftKey && Key.Oem5 == e.Key)) && (validatorDefn as FormatValidatorDefinition).format == "packedascii"))
        {
           e.Handled = true;
        }
    }

答案 3 :(得分:1)

部分是从@Josh借用的,与@Krushik有点类似,并且还引用了有关Difference between KeyEventArgs.systemKey and KeyEventArgs.Key的问题(回答了为何Josh必须使用SystemKey);其中,使用修饰键(例如Alt),e.Key返回Key.System,因此“真实”键位于e.SystemKey之内。

解决此问题的一种方法是,首先获取“真实”密钥,然后进行有条件的操作:

private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
    // Fetch the real key.
    var key = e.Key == Key.System ? e.SystemKey : e.Key;

    if ((Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt))
        && key == Key.Return)
    {
        // Execute your code.
    }
}

答案 4 :(得分:0)

以及:

如果My.Computer.Keyboard.ShiftKeyDown那么......

My.Computer.Keyboard.CtrlKeyDown

My.Computer.Keyboard.AltKeyDown

答案 5 :(得分:0)

这就是我的处理方式(使用PreviewKeyDown),假设我们正在寻找Alt + R ...

private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
    if ((Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)
       && e.SystemKey == Key.R)
    {
       //do whatever
    }
}

也许有人可以弄清楚为什么我不得不使用e.SystemKey而不是仅仅使用e.Key,也许是由于修改器的缘故?但这在我搜索修饰符+键时对我来说是完美的。