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?
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?
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();
}
}
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.
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();
}
}
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();
}
}
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.
One option is to assign an access key to a control with a label. You assign a shortcut based on a label related to the textbox.
To assign an access key to a control with a label
- Draw the label first, and then draw the other control.
-or-
Draw the controls in any order and set the TabIndex property of the label to one less than the other control.
Set the label's UseMnemonic property to true.
Use an ampersand (&) in the label's Text property to assign the access key for the label. For more information, see Creating Access Keys for Windows Forms Controls.
In the picture below, if you press ALT+Y the focus moves to the textbox.
© 2022 - 2024 — McMap. All rights reserved.