Reputation: 5549
I have a windows form which saves data on ButtonClick event but I also want to execute this event when user presses some key board shortcut such as :
CTRL + S
to save.
I tried form's KeyDown event
and KeyPress event
but they just wont fire.
I guess I am missing out something.
Private Sub frmExchangeSymbolMapping_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
If Asc(e.KeyChar) = Keys.Control AndAlso Asc(e.KeyChar) = Keys.E Then
MessageBox.Show("Testing")
End If
End Sub
I will accept c# answers too (If it can be converted to vb using online tools :P )
Upvotes: 0
Views: 3223
Reputation: 2297
If you set the Text for the button to &Save Alt-S will click the button assuming there isn't a menu intercepting the Ctrl-S.
Upvotes: 0
Reputation: 1014
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
Select Case msg.Msg
Case &H100, &H104
Select Case keyData
Case Keys.Control Or Keys.E
MessageBox.Show("Control + E Pressed")
Exit Select
End Select
Exit Select
End Select
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
Upvotes: 1
Reputation: 26209
My Solution is here in C#.
1. Set your Form
KeyPreview
Property to true
.
2. Subscribe to the KeyDown
Event of the Form
as below:
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
3. handle the KeyDown
event of Form
as below:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.S)
MessageBox.Show("Ctrl + S pressed!");
}
Complete Code:
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.S)
MessageBox.Show("Ctrl + S pressed!");
}
Upvotes: 0
Reputation: 7508
Set the KeyPreview
property of the form to true
. This will register all the key events with the form itself first and, if no shortcut is found, with the currently focused component.
Upvotes: 5