Sending keystrokes to control in .Net - c#

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

Related

Assigning "escape" key to a button in windows form in C#

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);
}

Get keydown event without a textbox

Im trying to do like that: If I press the key "P" a messagebox will open in the screen.But I need to do it without a textbox or other tool, I want to do that direct in the form.
I tried:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.P)
{ MessageBox.Show("Key P pressed"); }
}
Try with the KeyPress Event of the form. It just works fine.
Assuming this is Winforms, on the form you're trying to catch the event on, make sure to set
Form1.KeyPreview = true;
KeyPreview ensures that keyboard events anywhere on the particular form (such as to a textbox with focus) will still count as a keyboard event for the form itself.

Key down event on the slider in C#

I wanted to handle Arrow key press event on the slider control. I tried googling for it but almost all the links gave me information about handling it on the windows(overrideing WndProc or ProcessCmdKey).The KeyDwon and Key Up events aren't fired for the Arrow press. How can i handle it?
Look here.
Here's a short quote from there:
Certain keys, such as the TAB, RETURN, ESC, and arrow keys are handled by controls automatically. To have these keys raise the KeyDown event, you must override the IsInputKey method in each control on your form. The code for the override of the IsInputKey would need to determine if one of the special keys is pressed and return a value of true. Instead of overriding the IsInputKey method, you can handle the PreviewKeyDown event and set the IsInputKey property to true. For a code example, see the PreviewKeyDown event.
And here's the code sample from the PreviewKeyDown event from here (PreviewKeyDown):
// By default, KeyDown does not fire for the ARROW keys
void button1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
case Keys.Up:
if (button1.ContextMenuStrip != null)
{
button1.ContextMenuStrip.Show(button1,
new Point(0, button1.Height), ToolStripDropDownDirection.BelowRight);
}
break;
}
}
// PreviewKeyDown is where you preview the key.
// Do not put any logic here, instead use the
// KeyDown event after setting IsInputKey to true.
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
case Keys.Up:
e.IsInputKey = true;
break;
}
}
I'm presuming you're using a track bar control when you say slider control? If not, then this answer probably won't help.
Anyway, you need to set the OnKeyDown event for your track bar control. Something as simple as the following code will allow the user to use the left and right arrows to move from side to side.
private void trackBar1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Right) && (trackBar1.Value < trackBar1.Maximum))
trackBar1.Value += 1;
if ((e.KeyCode == Keys.Left) && (trackBar1.Value > trackBar1.Maximum))
trackBar1.Value -= 1;
}
You simply need to detect a key press, and then decide whether it's a left or right arrow, and then what to do from there.
I've tried it and the left and right arrows do trigger it for me. Again, if you're using a different slider control (there isn't any control called the slider control, so I'm assuming track bar) then it may be different.

How to set hotkeys for a Windows Forms form

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.

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?
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.

Categories