I would like to set hotkeys in my Windows Forms form. For example, Ctrl + N for a new form and Ctrl + S for save. How would I do this?
Set
myForm.KeyPreview = true;
Create a handler for the KeyDown event:
myForm.KeyDown += new KeyEventHandler(Form_KeyDown);
Example of handler:
// Hot keys handler
void Form_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.S) // Ctrl-S Save
{
// Do what you want here
e.SuppressKeyPress = true; // Stops other controls on the form receiving event.
}
}
You can also override ProcessCmdKey in your Form derived type like this:
protected override bool ProcessCmdKey(ref Message message, Keys keys)
{
switch (keys)
{
case Keys.B | Keys.Control | Keys.Alt | Keys.Shift:
// ... Process Shift+Ctrl+Alt+B ...
return true; // signal that we've processed this key
}
// run base implementation
return base.ProcessCmdKey(ref message, keys);
}
I believe it's more suitable for hotkeys. No KeyPreview needed.
If your window has a menu, you can use the ShortcutKeys property of System.Windows.Forms.ToolStripMenuItem:
myMenuItem.ShortcutKeys = Keys.Control | Keys.S;
In Visual Studio, you can set it in the property page of the menu item, too.
I'd like a KeyDown event for the Form and some code like this:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.Control | Keys.N))
{
CreateNew();
}
}
If you are trying to link them to menu items in your application, then you don't need any code. On the menu item, you can simply setup the shortcut key property and it will run the same event that you have configured for your menu item click.
I thought I'd put an update here since the newest answer is 5 years old. Specifically addressing the question portion regarding Menu hotkeys, you can manipulate the properties of your MenuStrip.MenuItem object, by setting the ShortcutKeys property. In Visual Studio you can do this in the form design window by opening the properties of your MenuStrip object. Once scrolled down to the the ShortcutKeys property, you can use VS interface to set your hot keys.
If you want a MenuStrip to underline a menu item, prefix the ampersand (&) char to the char of the desired hotkey. So for example if you want the "x" of Exit to be underlined, the property setting should be E&xit.
These property manipulations should yield a result similar to this*:
*Note: To display the shortcut key "Ctrl+N" change ShowShortcutKeys property to true.
You can set it using a hidden menu too, if you want. Just set the property of menu.visible = false;
First, you need to handle the KeyDown event, and then you can start watching out for your modifiers:
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.S)
{
//Do whatever
}
}
Of course, you need to make sure your form subscribes to the KeyDown event.
Related
I'm looking for a best way to implement common Windows keyboard shortcuts (for example Ctrl+F, Ctrl+N) in my Windows Forms application in C#.
The application has a main form which hosts many child forms (one at a time). When a user hits Ctrl+F, I'd like to show a custom search form. The search form would depend on the current open child form in the application.
I was thinking of using something like this in the ChildForm_KeyDown event:
if (e.KeyCode == Keys.F && Control.ModifierKeys == Keys.Control)
// Show search form
But this doesn't work. The event doesn't even fire when you press a key. What is the solution?
You probably forgot to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Control | Keys.F)) {
MessageBox.Show("What the Ctrl+F?");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
On your Main form
Set KeyPreview to True
Add KeyDown event handler with the following code
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.N)
{
SearchForm searchForm = new SearchForm();
searchForm.Show();
}
}
The best way is to use menu mnemonics, i.e. to have menu entries in your main form that get assigned the keyboard shortcut you want. Then everything else is handled internally and all you have to do is to implement the appropriate action that gets executed in the Click event handler of that menu entry.
You can even try this example:
public class MDIParent : System.Windows.Forms.Form
{
public bool NextTab()
{
// some code
}
public bool PreviousTab()
{
// some code
}
protected override bool ProcessCmdKey(ref Message message, Keys keys)
{
switch (keys)
{
case Keys.Control | Keys.Tab:
{
NextTab();
return true;
}
case Keys.Control | Keys.Shift | Keys.Tab:
{
PreviousTab();
return true;
}
}
return base.ProcessCmdKey(ref message, keys);
}
}
public class mySecondForm : System.Windows.Forms.Form
{
// some code...
}
If you have a menu then changing ShortcutKeys property of the ToolStripMenuItem should do the trick.
If not, you could create one and set its visible property to false.
From the main Form, you have to:
Be sure you set KeyPreview to true( TRUE by default)
Add MainForm_KeyDown(..) - by which you can set here any shortcuts you want.
Additionally,I have found this on google and I wanted to share this to those who are still searching for answers. (for global)
I think you have to be using user32.dll
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x0312)
{
/* Note that the three lines below are not needed if you only want to register one hotkey.
* The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); // The key of the hotkey that was pressed.
KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF); // The modifier of the hotkey that was pressed.
int id = m.WParam.ToInt32(); // The id of the hotkey that was pressed.
MessageBox.Show("Hotkey has been pressed!");
// do something
}
}
Further read this http://www.fluxbytes.com/csharp/how-to-register-a-global-hotkey-for-your-application-in-c/
Hans's answer could be made a little easier for someone new to this, so here is my version.
You do not need to fool with KeyPreview, leave it set to false. To use the code below, just paste it below your form1_load and run with F5 to see it work:
protected override void OnKeyPress(KeyPressEventArgs ex)
{
string xo = ex.KeyChar.ToString();
if (xo == "q") //You pressed "q" key on the keyboard
{
Form2 f2 = new Form2();
f2.Show();
}
}
In WinForm, we can always get the Control Key status by:
bool IsCtrlPressed = (Control.ModifierKeys & Keys.Control) != 0;
The VB.NET version of Hans' answer.
(There's a ProcessCmdKey function template in Visual Studio.)
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
If (keyData = (Keys.Control Or Keys.F)) Then
' call your sub here, like
SearchDialog()
Return True
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
End Class
I have a simple windows form in C#. my form has a bottun which in Click event is several codes and tasks.
i want to assign escape key on keyboard to this button. how can i do this?
Your form has a property CancelButton. Assign your button to this property. You can easily do that in property window of Visual Studio. Then your button will be clicked when hitting escape.
Set KeyPreview = true; for the form and then override form's OnKeyDown method something like this:
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Modifiers == Keys.None && e.KeyCode == Keys.Escape)
//your button click event handler call here like button1_Click(null, null);
}
I have this code:
private void button5_Click(object sender, EventArgs e)
{
Magnifier20070401.MagnifierForm mf = new Magnifier20070401.MagnifierForm();
mf.Show();
}
It shows the target form correctly. But instead of using a button click, I want to use Ctrl+M to show this form. If the users types Ctrl+M again, I want to close the the form.
How can I do this?
Edit:
This is what i did wich is working :
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode.ToString() == "M")
{
Magnifier20070401.MagnifierForm mf = new Magnifier20070401.MagnifierForm();
mf.Show();
}
}
In the constructor of Form1 i added:
this.KeyPreview = true;
So now when i click on Ctrl+M i see the new Form.
What i need now is how to make that if i click again on Ctrl+M it will close the new Form.
Maybe using a flag ?
Edit:
This is what i did now:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode.ToString() == "M")
{
if (mf == null)
{
mf = new Magnifier20070401.MagnifierForm();
mf.Show();
}
else
{
mf.Close();
this.Invalidate();
}
}
}
But even doing this.Invalidate(); i don't see the new Form closed.
But if im using put a breakpoint on the mf.Close(); and step into(F11) i see it close when making continue.
Why it dosen't close without using a breakpoint ?
You can add onKeyPress or onKeyDown
and check if Ctrl+M were pressed
private void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
if (((Control.ModifierKeys & Keys.Control) == Keys.Control)
&& (e.KeyChar == 'M'|| e.KeyChar == 'm'))
{
mf.Show();
}
You would use the InputBindings object. I think in your case, probably best to put that at the Window level (Window.InputBindings). More information here:
http://msdn.microsoft.com/en-us/library/system.windows.input.inputbinding.aspx
You can solve this in 2 ways.
If you are using a GUI interface, add a MenuItem control on your Menu, and put the Shortcut property to Ctrl+M then double click the MenuItem to edit the code, then call your launchMagnifier() function. If you do NOT want your menu to show, just set the visible properties to false. This keeps the menu hidden if you do not want it, yet still holds the functionality.
If you do not want the MenuItem, you can catch keys that are pressed in your form. So in your frmMain.cs form, add an event to capture keys, then when Ctrl+M is pressed, invoke launchMagnifier()
A few ways to do that.
On your form set the KeyPreview Property to true
Then add an OnKeyPress or OnKeyDown event handler to the form.
In that test for Ctrl-M and show / destroy the form and set handled (e.Handled) to true.
Any other keypress will be passed on to the currently focused control as it hasn't been handled.
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?
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.
Source :
https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-create-access-keys-with-windows-forms-label-controls?view=netframeworkdesktop-4.8
In the picture below, if you press ALT+Y the focus moves to the textbox.
My ActiveX control contains various shapes which are drawn. CTRL-A is used in the control to select all the objects. Similarly CTRL-C to copy, CTRL-V to paste etc.
However, when I insert this control within a Windows form in a .Net application, it does not receive these keyboard events. I tried adding a PreviewKey event, and this does allow certain keystrokes to be sent e.g. TAB, but not these modified keys.
Does anybody know how to redirect modified keystrokes to a user control?
Thanks.
It's possible that the ActiveX control doesn't have focus and is therefore not receiving the key events. You may want to handle the key events at the form level and then call the appropriate methods on your ActiveX control. If you set the KeyPreview property of your form to true your form will receive the key events for all controls on the form. That way, your shortcuts should work no matter what control currently has focus. Here is a quick example you can play with to test this out. Create a new form with several different controls on it and modify the code like so:
public Form1()
{
InitializeComponent();
KeyPreview = true; // indicates that key events for controls on the form
// should be registered with the form
KeyUp += new KeyEventHandler(Form1_KeyUp);
}
void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control)
{
switch (e.KeyCode)
{
case Keys.A:
MessageBox.Show("Ctrl + A was pressed!");
// activeXControl.SelectAll();
break;
case Keys.C:
MessageBox.Show("Ctrl + C was pressed!");
// activeXControl.Copy();
break;
case Keys.V:
MessageBox.Show("Ctrl + V was pressed!");
// activeXControl.Paste();
break;
}
}
}
No matter what control has focus when you enter the key combinations, your form's Form1_KeyUp method will be called to handle it.
You need to trap the keys and override the ProcessCmdKey method.
class MyDataGrid : System.Windows.Forms.DataGrid
{
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
...........
}
}
http://support.microsoft.com/kb/320584
KeyPreview is just the wrong method. Try using KeyUp or KeyDown, like this:
private void ControlKeyTestForm_KeyUp(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
this.label1.Text = "Ctrl+A pressed";
}
If you want the containing form to deal with shortcut keys remember to set the KeyPreview property on the form to true then set the KeyDown or KeyUp handlers in the form.
Use Control.ModifierKeys Property to check for Modifier keys.
For example, to check for shift key,
try if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) { }
Full example here:
http://msdn.microsoft.com/en-us/library/aa984219%28VS.71%29.aspx