How to detect modifier key states in WPF?

前端 未结 6 1536
粉色の甜心
粉色の甜心 2020-12-04 15:10

Is there some global constructs that I can use whenever I need to access whether the Control, Shift, Alt buttons are down? For instance inside MouseDown event o

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 15:20

    Partly borrowing from @Josh, and somewhat similar to @Krushik, and also referencing a question about the Difference between KeyEventArgs.systemKey and KeyEventArgs.Key (answering why Josh has to use SystemKey); wherein, with modifier keys (such as Alt), e.Key returns Key.System, and thus the 'real' key is within e.SystemKey.

    A way around this, is to first fetch the 'real' key, and then do your conditional:

    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.
        }
    }
    

提交回复
热议问题