Pass KeyDown event to other control

↘锁芯ラ 提交于 2020-01-15 05:58:29

问题


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?


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/27507946/pass-keydown-event-to-other-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!