问题
I have this textbox I use to capture keyboard shortcuts for a preferences config. I use a low-level keyboard hook to capture keys and also prevent them from taking action, e.g. the Windows key, but the Alt key still comes through and makes my textbox lose focus.
How can I block the Alt key, so the focus is kept unaltered at my textbox?
回答1:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt)
{
e.Handled = true;
}
}
回答2:
You can register for the keydown event and for the passed in args do this:
private void myTextBox_KeyDown(object sender, KeyEventArgs e)
{
if(e.Alt)
e.SuppressKeyPress = true;
}
And you register for the event like so:
this.myTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.myTextBox_KeyDown);
or if you're not using C# 1.0 you can simplify to this:
this.myTextBox.KeyDown += this.myTextBox_KeyDown;
来源:https://stackoverflow.com/questions/2660375/winforms-how-to-prevent-textbox-from-handling-alt-key-and-losing-focus