转发KeyPress事件 [英] Forward a KeyPress-event
问题描述
我有一个TextBox,想从另一个Form转发一个KeyPress事件.
I have a TextBox and would like to forward a KeyPress-event from another Form.
到目前为止,我有我的表格:
So far I have my Form:
private readonly Action<KeyPressEventArgs> m_KeyPress;
public KeyboardForm( Action<KeyPressEventArgs> keyPress )
{
m_KeyPress = keyPress;
}
protected override void OnKeyPress( KeyPressEventArgs e )
{
m_KeyPress( e );
base.OnKeyPress( e );
}
还有一个派生的TextBox,它初始化了Form:
And a derived TextBox, which initializes the Form:
var keyboardForm = new KeyboardForm( OnKeyPress );
keyboardForm.Show();
现在,将按预期方式(在Form中,然后在TextBox中)调用OnKeyPress方法.但是,什么都没有发生……当我按下"a"时,我希望在文本框中出现一个"a" ...
Now, the OnKeyPress-method gets called as expected (of the Form, then of the TextBox). But nevertheless nothing happens ... when I press 'a' I expected an 'a' to appear in my TextBox ...
有人知道这里有什么问题吗?
Does anyone have an idea what's the problem here?
它也不能与KeyDown
一起使用,并且附加到常规的公开事件KeyPress
也无济于事.我认为问题在于OnKeyPress
的显式调用.可以吗?
It is not working with KeyDown
, too, and attaching to the regular exposed event KeyPress
does not help me either. I think, that the problem is the explicit call of OnKeyPress
. Is it allowed?
推荐答案
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Form2 f = new Form2();
f.mEvent += new Form2.TestEvent(f_mEvent);
f.Show();
}
void f_mEvent(KeyPressEventArgs e)
{
textBox1.Text += e.KeyChar;
}
}
Form2:
public partial class Form2 : Form
{
public delegate void TestEvent(KeyPressEventArgs e);
public event TestEvent mEvent;
public Form2()
{
InitializeComponent();
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (mEvent != null)
{
mEvent(e);
}
base.OnKeyPress(e);
}
}
这篇关于转发KeyPress事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!