How can I print which keys are pressed?
Most of the time, every program using hotkeys allows the user to see which keys are actually pressed, but I'm not sure how this is done. For reference, see the following screenshot of a random program that displays what the button combination is:
How can I implement something like this? The event I'm reading is of type System.Windows.Forms.KeyEventArgs
. There are many keys that do not have a description of its actual meaning and several others that have imprecise meanings. Is there no solution other than defining the code for each key and manually displaying it?
Edit: For clarification, I want to get a convenient string representation of the keys that were pressed as shown in the screenshot above.
source to share
The event has bool properties for Alt
, Control
and Shift
.
KeyCode
type System.Windows.Forms.Keys . It has an attribute [Flags]
, but it only counts for Alt
, Control
and Shift
. All other keys have regular meanings.
private void showKeys(object sender, KeyEventArgs e)
{
List<string> keys = new List<string>();
if (e.Control == true)
{
keys.Add("CTRL");
}
if (e.Alt == true)
{
keys.Add("ALT");
}
if (e.Shift == true)
{
keys.Add("SHIFT");
}
switch (e.KeyCode)
{
case Keys.ControlKey:
case Keys.Alt:
case Keys.ShiftKey:
case Keys.Menu:
break;
default:
keys.Add(e.KeyCode.ToString()
.Replace("Oem", string.Empty)
);
break;
}
e.Handled = true;
textBox1.Text = string.Join(" + ", keys);
}
source to share
KeyEventArgs.KeyCode property ....
If you can use javascript u will have code for each key
and I found it quite interesting for Keyeventargs.Keycode http://www.asquare.net/javascript/tests/KeyCode.html
source to share
For a win form, you need to first set the KeyPreview property to true
. Thus, the pressed key should be detected even if one of the form's child forms has focus and the form itself does not.
Then redefine one of the following methods: OnKeyUp
, OnKeyDown
and OnKeyPress
.
protected override void OnKeyUp(KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.F1:
showHelpTopics();
break;
}
}
If you do not have a description of some of the keys, just search for msdn and you will find its details.