KeyDown : recognizing multiple keys

后端 未结 13 2657
悲&欢浪女
悲&欢浪女 2020-12-03 02:47

How can I determine in KeyDown that CtrlUp was pressed.

private void listView1_KeyDown(object sender, KeyEventArgs e)
{
           


        
相关标签:
13条回答
  • 2020-12-03 03:19

    you can try my working code :

    private void listView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Up)
        {
            if(e.Alt==true){
                //do your stuff
            }
        }
    }
    

    i use this code because i don't know why when i use :

    (e.Keycode == Keys>up && e.Alt==true)
    

    didn't work.

    0 讨论(0)
  • 2020-12-03 03:21

    In the KeyEventArgs there are properties Ctrl, Alt and Shift that shows if these buttons are pressed.

    0 讨论(0)
  • 2020-12-03 03:21

    You can use the ModifierKeys property:

    if (e.KeyCode == Keys.Up && (ModifierKeys & Keys.Control) == Keys.Control)
    {
        // CTRL + UP was pressed
    }
    

    Note that the ModifierKeys value can be a combination of values, so if you want to detect that CTRL was pressed regardless of the state of the SHIFT or ALT keys, you will need to perform a bitwise comparison as in my sample above. If you want to ensure that no other modifiers were pressed, you should instead check for equality:

    if (e.KeyCode == Keys.Up && ModifierKeys == Keys.Control)
    {
        // CTRL + UP was pressed
    }
    
    0 讨论(0)
  • 2020-12-03 03:23

    It took me a while to find the hint I ultimately needed when trying to detect [Alt][Right]. I found it here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/4355ab9a-9214-4fe1-87ea-b32dfc22946c/issue-with-alt-key-and-key-down-event?forum=wpf

    It boils down to something like this in a Shortcut helper class I use:

    public Shortcut(KeyEventArgs e) : this(e.Key == System.Windows.Input.Key.System ? e.SystemKey : e.Key, Keyboard.Modifiers, false) { }
    
    public Shortcut(Key key, ModifierKeys modifiers, bool createDisplayString)
    {
        ...
    } 
    

    After "re-mapping" the original values (notice the e.Key == System.Windows.Input.Key.System ? e.SystemKey : e.Key part), further processing can go on as usual.

    0 讨论(0)
  • 2020-12-03 03:23

    you have to remember the pressed keys (ie in a bool array). and set the position to 1 when its pressed (keydown) and 0 when up .

    this way you can track more than one key. I suggest doing an array for special keys only

    so you can do:

     if (e.KeyCode == Keys.Control)
     {
            keys[0] = true;
     }
    // could do the same with alt/shift/... - or just rename keys[0] to ctrlPressed
    
    if (keys[0] == true && e.KeyCode == Keys.Up)
     doyourstuff
    
    0 讨论(0)
  • 2020-12-03 03:24

    if (e.Control && e.Shift && e.KeyCode == Keys.A) {

    }

    0 讨论(0)
提交回复
热议问题