问题
How do you handle a KeyDown event when the ALT key is pressed simultaneously with another key in .NET?
回答1:
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.
回答2:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyData != (Keys.RButton | Keys.ShiftKey | Keys.Alt))
{
// ...
}
}
回答3:
Something like:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt)
{
e.Handled = true;
// ,,,
}
}
回答4:
This is the code that finally Works
if (e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z && e.Alt){
//Do SomeThing
}
回答5:
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++;
}
}
回答6:
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)
{
}
}
来源:https://stackoverflow.com/questions/2146970/handle-the-keydown-event-when-altkey-is-pressed