I need to set Keyboard Shortcut in WinForm checkbox. For check or uncheck.
I don't know the possibility of this,.
But With the Help of arrow keys and Space Key it can be done.
My requirement i开发者_运维技巧s like Below,..
Alt + C - Checked
Alt + U - Un checked.
Is Any Possibilities is there?.
You can manually check for the required key combination in form keydown like this (Assuming C#):- you should try some other key combination because of reserved keyboard mnemonics as Cody Gray mentioned.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// When the user presses both the 'Alt' key and 'C' key,
if (e.Alt && e.KeyCode.ToString() == "C")
{
//check the checkbox
this.checkBox1.Checked= true;
}
// When the user presses both the 'Alt' key and 'U' key,
if (e.Alt && e.KeyCode.ToString() == "U")
{
//Uncheck the checkbox
this.checkBox1.Checked= false;
}
}
Check Form.KeyPress property to get or set a value indicating whether the form will receive key events before the event is passed to the control that has focus.
You can do it with mnemonics...(if you don't mind including the key you want to use for the shortcut within the text of the checkbox).
- Make sure UseMnemonic is set to true on your checkBox (I think this is the default)
- Put the key you want to use in the text of the checkbox prefixed with an ampersand (e.g., &Check)
...then the key will be shown underlined in the text when the alt key is pressed & pressing the mnemonic key will alternatively check & uncheck the checkbox.
You can achieve this by overriding the processCmdKey
of the form control. You can set up all your shortcuts this way. Check the following code below (VB.NET):
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean
If keyData = Keys.N Then
''call a method that check or uncheck the control
End If
''you can even combine modifiers keys
If keyData =keys.Control + Keys.T Then
''do something
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
精彩评论