Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 589
Shekhar Avatar asked Mar 23 '10 10:03

Shekhar


People also ask

For which command is Ctrl F shortcut key?

To quickly find a shortcut in this article, you can use Search. Press Ctrl+F, and then type your search words. If an action that you use often does not have a shortcut key, you can record a macro to create one.

Which key is used as a shortcut key to copy the text?

Select the text you want to copy and press Ctrl+C. Place your cursor where you want to paste the copied text and press Ctrl+V.


3 Answers

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();
     }
}
like image 75
Mangesh Chaurasia Avatar answered Oct 14 '22 04:10

Mangesh Chaurasia


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();
    }
}
like image 42
Wayne Avatar answered Oct 14 '22 03:10

Wayne


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.

like image 27
Aseem Gautam Avatar answered Oct 14 '22 02:10

Aseem Gautam