How can you create Alt shortcuts in a Windows Forms application?

ぃ、小莉子 提交于 2019-12-05 16:16:13

问题


I'd like to create keyboard shortcuts for some controls in my Windows Forms application.

Example:

Notice the underlined, F E V P B.

I have a label and a textbox control. I'd like to associate that Alt keyboard shortcut to the label and the textbox. So if someone presses Alt + B, focus is given to the associated textbox. Is there a way to create this association?


回答1:


When the label receives focus from pressing its accelerator key (set using the &), it forwards the focus to the next control in the tab order, since labels are not editable. You need the textbox to be next control in the tab order.

To view and correct the tab order of your form, use the View + Tab Order command in the IDE. Using TabPages or other containers adds a level of nesting to the tab order (e.g., 1.1, 1.2 instead of just 1 and 2), but if the label and textbox are within the same container it shouldn't be too hard to set properly.




回答2:


Type &File or &Edit and you will get underline. That will automatically bind underlined letters with Alt keyword for shortcut.

EDIT. You question has modified so I'd like to keep up with my answer. You would like to catch some keys combination (Alt + F) and set a focus to the text box.

You may try this solution using KeyDown event of the main form.

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Alt && e.KeyCode == Keys.F)
        {
            this.textBox1.Focus();
        }
    }

To achieve this, you have to additionally set KeyPreview property of the form to true.




回答3:


this.KeyDown += new KeyEventHandler(Form1_KeyDown);

void Form1_KeyDown(object sender, KeyEventArgs e) 
{ 
 if (e.Alt && e.KeyCode == Keys.W)
 { 
   btnShowConstructionCdFun(); 
 } 
}


来源:https://stackoverflow.com/questions/4625820/how-can-you-create-alt-shortcuts-in-a-windows-forms-application

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