6

How do you handle a KeyDown event when the ALT key is pressed simultaneously with another key in .NET?

knueser
  • 357
  • 3
  • 14
Jedi Master Spooky
  • 5,629
  • 13
  • 57
  • 86

6 Answers6

7

The KeyEventArgs class defines several properties for key modifiers - Alt is one of them and will evaluate to true if the alt key is pressed.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
5
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Alt && e.KeyData != (Keys.RButton | Keys.ShiftKey | Keys.Alt))
    {
        // ...
    }
}
kor_
  • 1,510
  • 1
  • 16
  • 36
2

Something like:

   private void Form1_KeyDown(object sender, KeyEventArgs e)
   {
        if (e.Alt)
        {
            e.Handled = true;
            // ,,,
        }
    }
H H
  • 263,252
  • 30
  • 330
  • 514
2

This is the code that finally Works

if (e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z &&  e.Alt){
     //Do SomeThing
}
Jedi Master Spooky
  • 5,629
  • 13
  • 57
  • 86
  • 2
    how will your spanish and french users like this? – No Refunds No Returns Jan 27 '10 at 13:36
  • Do the special characters in non-English languages (e.g ê) fall between key codes A-Z? I think the answer is no, but not certain. Sorry to bump an old post but I just stumbled upon it. – XtrmJosh Jan 30 '14 at 21:04
  • 3
    You mean English people don't use digit and punctuation? Seriously, this answer is not correct - almost every other are. – Benlitz Dec 11 '14 at 06:53
0

I capture the alt and down or up arrow key to increment the value of a numericUpDown control. (I use the alt key + down/up key because this form also has a datagridview and I want down/up keys to act normally on that control.)

    private void frmAlzCalEdit_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Alt && e.KeyCode == Keys.Down)
        {
            if (nudAlz.Value > nudAlz.Minimum) nudAlz.Value--;

        }
        if (e.Alt && e.KeyCode == Keys.Up)
        {
            if (nudAlz.Value < nudAlz.Maximum) nudAlz.Value++;
        }

    }
Jim Lahman
  • 2,691
  • 2
  • 25
  • 21
0

Create a KeyUp event for your Form or use a library like I did to get a GlobalHook so you can press these keys outside the form.

Example:

 private void m_KeyboardHooks_KeyUp(object sender, KeyEventArgs e)
                {
                    if ( e.KeyCode == Keys.Alt || e.KeyCode == Keys.X)
                    {     


                    }
                }
Hesein Burg
  • 329
  • 3
  • 13