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:

enter image description here

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.

+3


source to share


4 answers


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);
}

      

+1


source


KeyEventArgs.KeyCode property ....

If you can use javascript u will have code for each key



Key codes in javascript

and I found it quite interesting for Keyeventargs.Keycode http://www.asquare.net/javascript/tests/KeyCode.html

0


source


You can get the witch key pressed by this code (for one key press or multiple keys, set the KeyPreview form to true)

    private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        label1.Text = null;
        label1.Text=e.Modifiers.ToString();
    }

      

0


source


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.

0


source







All Articles