Capturing Ctrl+A shortcut key - c#

I need to capture a kepress combo on the keyboard so i can override the standard function, i've tried the following:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
{
MessageBox.Show("Hello");
}
}
But when pressing Ctrl+A the message is not triggered. The end aim is to override the windows shortcut 'select all' in a DataGridView within the Form1 to ensure only certain rows are selected when Ctrl+A is pressed in the form window.

First, ensure that Form1 property
KeyPreview = true
Next, do not forget to handle the message (you don't want DataGridView process the message and do SelectAll)
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
{
e.Handled = true; // <- do not pass the event to DataGridView
MessageBox.Show("Hello");
}
}
So you preview KeyDown on the Form1 (KeyPreview = true), perform the required action, and prevent DataGridView from executing select all (e.Handled = true)

In general to handle a shortcut key, you can override ProcessCmdKey. By overriding this method, you can handle the key combination:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.A))
{
MessageBox.Show("Control + A");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Returning true, means it's handled by your code and the key will not pass to the child control. So it's enough to override this method at form level.
But if you are talking specifically about DataGridView to customize the Ctrl + A combination, you can override ProcessDataGridViewKey method of the DataGridView:
public class MyDataGridView : DataGridView
{
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
{
if (e.KeyData == (Keys.A | Keys.Control))
{
MessageBox.Show("Handled");
return true;
}
return base.ProcessDataGridViewKey(e);
}
}

Just for the records: This can be done with KeyPress too, because the Ctrl+Letter keys are "special":
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar=='\u0001') //Ctrl+A, B=2, C=3 ...
{
MessageBox.Show("Control + A");
}
}

Related

Autohide MenuStrip - How to activate it when showing?

I have a MenuStrip and I make it AutoHide using following code. It hides/shows prefect but when a control get focus, by pressing Alt key, MenuStrip shows but it is not active and there is not small underline under shortcut keys for example under 'F' for File , and pressing 'F' will not open it). How can I correctly active it?
Note: I used MenuDeactivate instead of it but it did not work prefect.
bool menuBarIsHide = true;
bool altKeyIsDown = false;
bool alwaysShowMenuBar=false;
//KeyPreview is true;
//for prevent glitch(open/close rapidly)
void Form1_KeyUp(object sender, KeyEventArgs e)
{
if ((Control.ModifierKeys & Keys.Alt) != 0)
altKeyIsDown = false;
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if ((Control.ModifierKeys & Keys.Alt) != 0)
{
if (altKeyIsDown)
return;
if (!alwaysShowMenuBar)
{
if (menuBarIsHide)
{
menuBar.Show();
menuBarIsHide = false;
//manage container height
}
else
{
menuBar.Hide();
menuBarIsHide = true;
//manage container height
}
}
}
}
You can override ProcessCmdKey to handle Alt key to toggle the menu visibility. Also to activate menu, call internal OnMenuKey method of MenuStrip. Also handle MenuDeactivate to make the menu invisible after finishing your work with menu, but you need to make the menu invisible using BeginInvoke.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Alt | Keys.Menu))
{
if (!this.menuStrip1.Visible)
{
this.menuStrip1.Visible = true;
var OnMenuKey = menuStrip1.GetType().GetMethod("OnMenuKey",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
OnMenuKey.Invoke(this.menuStrip1, null);
}
else
{
this.menuStrip1.Visible = false;
}
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void menuStrip1_MenuDeactivate(object sender, EventArgs e)
{
this.BeginInvoke(new Action(() => { this.menuStrip1.Visible = false; }));
}

KeyPress F1 does not work C#

I'm designing a device app. Compact Framework 2.0
I want the user to press F1 to navigate to the next screen, but it does not work.
Can't seem to find a solution.
Is it possible?
This is how I normally use Keypress:
This works:
if (e.KeyChar == (char)Keys.M)
{
MessageBox.Show("M pressed");
e.Handled = true;
}
This dos NOT work:
if (e.KeyChar == (char)Keys.F1)
{
MessageBox.Show("F1 pressed");
e.Handled = true;
}
try this
private void Form1_Load(object sender, EventArgs e)
{
this.KeyPreview = true;
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode.ToString() == "F1")
{
MessageBox.Show("F1 pressed");
}
}
Refer This
You can override the ProcessCmdKey method of your form class and use keyData == Keys.F1 to check whether F1 is pressed. Above link has example as follows.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.F1)
{
MessageBox.Show("You pressed the F1 key");
return true; // indicate that you handled this keystroke
}
// Call the base class
return base.ProcessCmdKey(ref msg, keyData)
}
Some keys(like f1,f2,arrow keys ,tab ....)cannot be "captured" by keychar for that you need to use keycode:
if (e.KeyCode == Keys.F1)
{
// do stuff
}
keychar property - http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.keychar.aspx
Use KeyDown instead of KeyPress:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.F1)
{
// your code here
}
}
Also set KeyPreview to true

Form1_KeyDown not working as per required

I have taken a link button on my form and on KeyDown event I write as follows to move the link button to left
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
linkLabel1.Left = linkLabel1.Left + 5;
}
}
But this is not moving the linklabel as per required, can some one tell where I went wrong
This too didn't work
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Left:
linkLabel1.Left = linkLabel1.Left + 5;
break;
default:
return;
}
}
set form1`s KeyPreview = true.
it works.
I think its to do with the interception of events by the linklabel. With the link label present on the form the key down event will not be raised to the form.
Setting KeyPreview to true (on the form) goes someway towards fixing this. You should then get the event raised, though you might still have problems with the arrow keys.
Update:
Ok, this should work, add this:
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Left)
{
linkLabel1.Left = linkLabel1.Left + 5;
}
return base.ProcessDialogKey(keyData);
}
When you want to move a Control, you have to reconfigure it's Control.Location property.
So simply add or remove some dots form the Location.[X/Y].Property and that's all!
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
// have we space?
if(linkLabel1.Location.X >= 4)
// 5 dots to the left side
linkLabel1.Location = new Point(linkLabel1.Location.X - 5, linkLabel1.Location.Y);
}
}
EDIT:
msdn
Location is a Point and a Point has a (x,y) - Coordinate.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (e.KeyCode == Keys.Left)
{
linkLabel1.Left = linkLabel1.Left + 5;
}
return base.ProcessCmdKey(ref msg, keyData);
}

Unable to capture Enter Key

I have a simple form by which I take input:
12 Buttons, 1 Textbox (disabled & read-only)
this is what I do to handle input
Login_KeyDown() is common method I call for all the KeyDown of every UI component & the form itself..
private void Login_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
Application.Exit();
}
else if (e.KeyCode == Keys.NumPad9 || e.KeyCode == Keys.D9)
{
button3.BackgroundImage = Properties.Resources.button_hover;
button3.ForeColor = Color.White;
pin.Text = pin.Text + "9";
}
else if (e.KeyCode == Keys.Back)
{
button11.BackgroundImage = Properties.Resources.button_hover;
button11.ForeColor = Color.White;
if (pin.Text.Length > 0)
pin.Text = pin.Text.Substring(0, pin.Text.Length - 1);
}
else if (e.KeyCode == Keys.Enter)
{
MessageBox.Show(pin.Text);
}
}
This code works fine when I start the app but after I have clicked on any component, rest of the code works fine but "Enter Key Condition" doesn't work.
My guess is as "Enter Key Condition" is not working for UI components or something like that.
I have also tried using "Key Press Event" which uses KeyPressEventArgs then checking KeyChar == 13 but that is also not working.
What is the problem, and how can I solve it?
p.s.
I have not set any button click events for any button, the app is 100% KBoard based.
Check out PreviewKeyDown. Return raises that event on button controls.
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Return)
MessageBox.Show("I found return");
}
Or alternatively you can force it to raise those special keys in the KeyDown Event by using:
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Return)
e.IsInputKey = true;
}
More information: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx
Have you tried to use
Keys.Return
Instead
Edit:
Just thought of this. Do you have the acceptbutton set for the main form?
This is because your Form has AcceptButton defined. For example, you have a "OK", "Accept" or "Confirm" button with DialogResult set to "OK". This tells its parent form that there is an AcceptButton, and the Enter event on the form would go to this button.
What you should do is to catch the Enter key at form level. Add this code to the form:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ((this.ActiveControl == myTextBox) && (keyData == Keys.Return))
{
//do something
return true;
}
else
{
return base.ProcessCmdKey(ref msg, keyData);
}
}

How do I capture the enter key in a windows forms combobox

How do I capture the enter key in a windows forms combo box when the combobox is active?
I've tried to listen to KeyDown and KeyPress and I've created a subclass and overridden ProcessDialogKey, but nothing seems to work.
Any ideas?
/P
Hook up the KeyPress event to a method like this:
protected void myCombo_OnKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
MessageBox.Show("Enter pressed", "Attention");
}
}
I've tested this in a WinForms application with VS2008 and it works.
If it isn't working for you, please post your code.
In case you define AcceptButton on your form, you cannot listen to Enter key in KeyDown/KeyUp/KeyPress.
In order to check for that, you need to override ProcessCmdKey on FORM:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if ((this.ActiveControl == myComboBox) && (keyData == Keys.Return)) {
MessageBox.Show("Combo Enter");
return true;
} else {
return base.ProcessCmdKey(ref msg, keyData);
}
}
In this example that would give you message box if you are on combo box and it works as before for all other controls.
or altertatively you can hook up the KeyDown event:
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter pressed.");
}
}
private void comboBox1_KeyDown( object sender, EventArgs e )
{
if( e.KeyCode == Keys.Enter )
{
// Do something here...
} else Application.DoEvents();
}
Try this:
protected override bool ProcessCmdKey(ref Message msg, Keys k)
{
if (k == Keys.Enter || k == Keys.Return)
{
this.Text = null;
return true;
}
return base.ProcessCmdKey(ref msg, k);
}
It could be that your dialog has a button that's eating the enter key because it's set to be the AcceptButton in the form property.
If that's the case then you solve this like this by unsetting the AcceptButton property when the control gets focus then resetting it back once the control loses focus ( in my code, button1 is the accept button )
private void comboBox1_Enter(object sender, EventArgs e)
{
this.AcceptButton = null;
}
private void comboBox1_Leave(object sender, EventArgs e)
{
this.AcceptButton = button1;
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
MessageBox.Show("Hello");
}
}
I have to admit not liking my own solution as it seems a little hacky to unset/set the AcceptButton property so if anyone has a better solution then I'd be interested
protected void Form_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13) // or Key.Enter or Key.Return
{
MessageBox.Show("Enter pressed", "KeyPress Event");
}
}
Don't forget to set KeyPreview to true on the form.

Categories

Resources