How to assign a shortcut key (something like Ctrl+F) to a text box in Windows Forms?

最后都变了- 提交于 2019-12-09 09:46:32

问题


I am building a tool using C#. It's a Windows application. I have one text box on a form, and I want to assign focus to that text box when the user presses Ctrl + F or Ctrl + S.

How do I do this?


回答1:


Capture the KeyDown event and place an if statement in it to check what keys were pressed.

private void form_KeyDown(object sender, KeyEventArgs e)
{
    if ((e.Control && e.KeyCode == Keys.F) || (e.Control && e.KeyCode == Keys.S)) {
        txtSearch.Focus();
    }
}



回答2:


One way is to override the ProcessCMDKey event.

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Control | Keys.S))
    {
        MessageBox.Show("Do Something");
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

EDIT: Alternatively you can use the keydown event - see How to capture shortcut keys in Visual Studio .NET.




回答3:


Add an event that catches a key press on the form, analyse the key press and see if it matches one of your shortcut keys and then assign focus.




回答4:


1st thing Make sure that the Your Windows Form property is "KeyPreview=true"

2nd Thing Open Form Event Property And double click on "KeyDown" And Write The Following code inside The Body of Event:-

private void form1_KeyDown(object sender, KeyEventArgs e)
{
     if ((e.Control && e.KeyCode == Keys.F) || (e.Control && e.KeyCode ==Keys.S)) 
     {
           TextBox1.Focus();
     }
}


来源:https://stackoverflow.com/questions/2499095/how-to-assign-a-shortcut-key-something-like-ctrlf-to-a-text-box-in-windows-fo

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