Reputation: 11994
I am using Visual Studio 2010 to create a visual C# application, and I want to include some options in my application's preferences for customization of keyboard shortcuts using some sort of text box input. I understand how to record keyboard input, and how to save it to the user application settings, but I can not find any input controls that have this functionality.
I.e. something like this:
But using windows forms (Note: The above is from Divvy for OS X from the app store).
Is there any built-in functionality to handle this? Are there any good libraries or custom inputs I could use?
Otherwise, any suggestions on how to go about implementing something like this?
Solution:
Using Bas B's answer and some other logic:
private void fShortcut_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Back)
{
Keys modifierKeys = e.Modifiers;
Keys pressedKey = e.KeyData ^ modifierKeys; //remove modifier keys
if (modifierKeys != Keys.None && pressedKey != Keys.None)
{
//do stuff with pressed and modifier keys
var converter = new KeysConverter();
fShortcut.Text = converter.ConvertToString(e.KeyData);
//At this point, we know a one or more modifiers and another key were pressed
//modifierKeys contains the modifiers
//pressedKey contains the other pressed key
//Do stuff with results here
}
}
else
{
e.Handled = false;
e.SuppressKeyPress = true;
fShortcut.Text = "";
}
}
The above is a way to tell when a valid shortcut combination is entered by checking if both modifier keys, and another key is pressed.
Upvotes: 4
Views: 2474
Reputation: 27105
You could have the user enter the preferred shortcut in a TextBox, then handle the KeyDown event, for instance:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
Keys modifierKeys = e.Modifiers;
Keys pressedKey = e.KeyData ^ modifierKeys; //remove modifier keys
//do stuff with pressed and modifier keys
var converter = new KeysConverter();
textBox1.Text = converter.ConvertToString(e.KeyData);
}
Edit: Updated to include Stecya's answer.
Upvotes: 4