我有一个按钮 - button1click和textbox,当我输入内容并按回车键时,我想从button1click运行代码。
如果不将整个代码从button1click复制到EnterPressed中,我怎么能这样做?
private void button1click(object sender, EventArgs e)
{
//Some Code
}
void EnterPressed(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Execute code from button1
}
}
也许是这样的?但是我收到了错误...
void EnterPressed(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1click(object sender, EventArgs e)
}
}
答案 0 :(得分:6)
只需让button1_click调用一个方法,然后就可以从任何地方调用相同的方法。所以在你的例子中:
private void button1click(object sender, EventArgs e)
{
Foo();
}
void EnterPressed(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Foo();
}
}
void Foo()
{
//Do Something
}
我个人不会手动调用另一个控件的事件。
答案 1 :(得分:1)
void EnterPressed(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1click(sender, EventArgs.Empty);
}
}