简体   繁体   中英

Keys.Numpad0 comes in as Keys.System when ALT is pressed

I am trying to detect hotkeys of ALT+1 through ALT+9 but when ALT is pressed the key comes in as Key.System. When CTRL+NumPad0 is pressed it key is Key.NumPad0 which is correct.

private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
    bool isAlt = Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt);
    bool isCtrl = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);

    string ctrlMod = string.Empty;

    if (isAlt)
    {
        ctrlMod = "alt + " + e.Key.ToString();
    }

    if (isCtrl)
    {
        ctrlMod = "ctrl + " + e.Key.ToString();
    }

    Debug.WriteLine("Key is " + ctrlMod);
}

ALT+NumPad0 through ALT+NumPad9 produces:

Key is alt + System

Ctrl works properly

Key is ctrl + NumPad1
Key is ctrl + NumPad2
Key is ctrl + NumPad3

You could use the Keyboard.Modifiers and KeyEventArgs.SystemKey properties to detect ALT+1 through ALT+9 :

private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (Keyboard.Modifiers == ModifierKeys.Alt)
    {
        string ctrlMod = "alt + " + e.SystemKey.ToString();
        Debug.WriteLine("Key is " + ctrlMod);
    }
}   

private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
    bool isAlt = Keyboard.Modifiers == ModifierKeys.Alt;
    bool isCtrl = Keyboard.Modifiers == ModifierKeys.Control;

    string ctrlMod = string.Empty;

    if (isAlt)
    {
        ctrlMod = "alt + " + e.SystemKey.ToString();
    }

    if (isCtrl)
    {
        ctrlMod = "ctrl + " + e.Key.ToString();
    }

    Debug.WriteLine("Key is " + ctrlMod);
}

I think maccettura is right and its to do with 'Windows Alt Codes'. I can get around it using

if (Keyboard.IsKeyDown(Key.NumPad0)) { } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM