tags:

views:

2222

answers:

6

How can I determine in KeyDown that Ctrl + Up was pressed.

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

can't work, because never both keys are pressed exactly in the same second. You always to at first the Ctrl and then the other one...

A: 

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
Niko
+3  A: 

You can check the modifiers of the KeyEventArgs like so:

private void listView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Up && e.Modifiers == Keys.Control)
    {
        //do stuff
    }
}

MSDN reference

Garry Shutler
+1  A: 

From the MSDN page on KeyEventArgs:

if (e.KeyCode == Keys.F1 && (e.Alt || e.Control || e.Shift))
{
    ...
Matt Hamilton
A: 

Hi, in the KeyEventArgs there are propartys Control, ALt, Shift that shows if these buttons are preseed Best Regards, iordan

IordanTanev
+1  A: 

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
}
Fredrik Mörk
A: 

None of these work for me. I'm trying to implement Ctrl-Tab (or Ctrl-A) in a combobox. What works is F1 or Ctrl-F1, but I don't want to use those. Here's the working code:

  private void cboProducts_KeyDown(object sender, KeyEventArgs e)

      if (e.KeyCode==Keys.F1  && e.Control) // works for F1
      {
          SendKeys.SendWait("{DOWN}");
      }

Why can't I do Ctrl-Tab or even Ctrl-A? Is there something about Combobox that won't allow tabs or letters?

T Cook