我有一个TextBox,想从另一个表单转发一个KeyPress-event。
到目前为止,我有了我的表单:
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,它初始化表单:
var keyboardForm = new KeyboardForm( OnKeyPress );
keyboardForm.Show();现在,OnKeyPress-method会像预期的那样被调用(表单,然后是TextBox)。但不管怎样,什么也没发生。当我按下'a‘时,我预计我的TextBox中会出现一个'a’...
有没有人知道问题出在哪里?
它也不能与KeyDown一起工作,并且附加到常规的公开事件KeyPress对我也没有帮助。我认为,问题在于OnKeyPress的显式调用。是允许的吗?
发布于 2009-07-07 03:37:55
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);
}
}发布于 2009-07-08 02:44:00
这应该可以做你想要的事情。使键盘窗体上的按钮文本基于SendKey characters。例如,如果想要小写a,只需将键盘按钮文本放入"a“即可。如果你想要一个退格键,只需要把“退格键”作为按钮的文本。所有键盘按钮单击事件都可以注册ButtonClick函数
键盘形式:
public partial class KeyboardForm : Form
{
public delegate void ButtonPressed(string keyPressed);
public event ButtonPressed ButtonPressedEvent;
public KeyboardForm()
{
InitializeComponent();
}
private void ButtonClick(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
if ((ButtonPressedEvent != null))
{
ButtonPressedEvent("{"+button.Text+"}");
}
}
}
}用户可在其中键入内容的带有文本框的表单:
public partial class Form1 : Form
{
private KeyboardForm mKeyboardForm = new KeyboardForm();
private bool mIsKeyboardCode = false;
public Form1()
{
InitializeComponent();
mKeyboardForm.ButtonPressedEvent += new KeyboardForm.ButtonPressed(KeyboardFormButtonPressedEvent);
}
void KeyboardFormButtonPressedEvent(string keyPressed)
{
mIsKeyboardCode = true;
textBox1.Focus();
SendKeys.SendWait(keyPressed.ToString());
mKeyboardForm.Focus();
mIsKeyboardCode = false;
}
private void TextBoxKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ControlKey)
{
if (!mKeyboardForm.Visible)
{
mKeyboardForm.Show(this);
e.Handled = true;
}
}
else if (!mIsKeyboardCode)
{
mKeyboardForm.Hide();
}
}
}注意:我没有使用包含表单的扩展文本框。我认为在自定义文本框中显示/隐藏表单不是一个好的设计。
发布于 2018-12-09 05:32:05
如果窗体上有一个捕捉Enter键按下的按钮,则可以使用以下代码将enter键作为普通的KeyPreview键进行处理:
void button_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
e.IsInputKey = true;
}
}https://stackoverflow.com/questions/1088023
复制相似问题