I am writing a C# WinForms application, .NET 4.0.
I have a WinForms Control
on a Form
. After user starts typing something using keyboard, another Control
appears. That Control
is some kind of text input. I'd like to send user input to that Control
. Of course, after it gets focused, it receives all user keyboard input. But as user starts typing before Control
appears, I have to pass first KeyDown
event to that control after I call it's Show
and Focus
methods.
SendKeys.Send method is a way of doing something similar. But that is so complicated, and seems to be unsafe. I have just a value of Keys
enumeration from KeyData
property of KeyEventArgs
, I'd like to use it, not transform it to some strange string.
Is there any good way to pass KeyDown
event from one control to another?
Any reason you can't just pass the event onto the "child control" ? Below example is KeyPress but the same idea applies for KeyDown
//Parent Control Visible
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
richTextBox1_KeyPress(sender, e);
}
//Child Control Hidden
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
richTextBox1.Text += e.KeyChar.ToString();
}
You can use PreviewKeyDown
on Form
.
Suppose you want to send keyboard inputs to TextBox textBox1
:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.PreviewKeyDown+= Form1_OnPreviewKeyDown;
textBox1.Visible = false;
}
private bool _textboxEnable = false;
private void Form1_OnPreviewKeyDown(object sender, PreviewKeyDownEventArgs previewKeyDownEventArgs)
{
if (!_textboxEnable) textBox1.Visible = true;
if (!textBox1.Focused) textBox1.Focus();
}
}
You can make a custom control which inherites the a textbox. YOu can place that custom control instead. In that custom control you can write a method which calls it:
public class MyTextBox : TextBox
{
public void TriggerKeyPress(KeyPressEventArgs e)
{
this.OnKeyPress(e);
}
}
If you dont want to make use of custom controlls you can make an extension to a textbox and use reflection to call it:
public static class TextBoxExtensions{
public static void TriggerKeyPress(this TextBox textbox, KeyPressEventArgs e)
{
MethodInfo dynMethod = textbox.GetType().GetMethod("OnKeyPress",
BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(textbox, new object[]{ e });
}
}
But with both methods you should know: This will not add the text from one object to another. To do that you will have to write that in your code manually.