简体   繁体   中英

C# How can I give a textbox focus when a key is pressed?

When the '-' minus key is pressed I want to jump to a certain textbox on my form and have the cursor flashing in that textbox. How can I do this?

Thanks Steven

You must handle the KeyDown event for your form, and check for the "-" key. Try this:

private void form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if (e.KeyCode = Keys.OemMinus)
    {
            textBox1.Focus();
    }
}
You can handle the key press event in the form as following.

 void Form1_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (e.KeyChar == 45)
                {
                   //Higlight the text box. Call the Select() method of the textbox
                }
            }

You need to create a event that set focus to certain Text Box,

next You need to create a key listener that fire that event when the '-' is pressed, the You need to add that listener in the palace where this functionality is available.

txtBox.Focus();

您必须获取表单的onKeyDown事件,并且您可以执行类似textbox.focus();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM