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?
KeyPreview
property to true
KeyPress
event to your parent formSet 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With