WinForms: How to prevent textbox from handling alt key and losing focus?

Deadly 提交于 2019-12-11 03:38:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!