Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all KeyPress events as a UserControl in C#?

I've read quite some articles now about key press events but I can't figure out how to get them. I know that only the current control with keyboard focus gets the press events. But how can i ensure that my user control has it?

Tried this without luck:

public partial class Editor : UserControl

this.SetStyle(ControlStyles.Selectable, true);
this.TabStop = true;
...
//take focus on click
protected override void OnMouseDown(MouseEventArgs e)
{
    this.Focus();
    base.OnMouseDown(e);
}
...
protected override bool IsInputKey(Keys keyData)
{
   return true;
}

And also this:

//register global keyboard event handlers
private void Editor_ParentChanged(object sender, EventArgs e)
{
    if (TopLevelControl is Form)
    {
        (TopLevelControl as Form).KeyPreview = true;
        TopLevelControl.KeyDown += FCanvas_KeyDown;
        TopLevelControl.KeyUp += FCanvas_KeyUp;
        TopLevelControl.KeyPress += FCanvas_KeyPress;
    }
}

The latter gave me the key down and up events, but still no key press. Is there any other method i can use to just get every down/up/press events when my control inherits from UserControl?

Edit: As there was a comment linking another SO question: It's important that I also get the KeyPress event, since it sends the correct character on every keyboard no matter which language. This is important for text writing. If you only get the individual keys you have to process them into the correct character on your own. But maybe there is a convenience method to transform the pressed keys into a localized character?

like image 309
thalm Avatar asked Oct 02 '22 04:10

thalm


1 Answers

  • Set your parent form's (contains the usercontrol) KeyPreview property to true
  • Add a new KeyPress event to your parent form

Set the parent form keypress event to forward the event to your usercontrol:

private void parentForm_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Forward the sender and arguments to your usercontrol's method
            this.yourUserControl.yourUserControl_KeyPress(sender, e);
        }

Replace the yourUserControl1_KeyPress method with your own method, which you want to run each time the user presses a button (the button is pressed down and then released).

You can also create a new KeyPress handler to your usercontrol, and forward the sender and KeyPressEventArgs objects there, as in this example.

like image 100
W0lfw00ds Avatar answered Oct 13 '22 11:10

W0lfw00ds