简体   繁体   English

C#从另一个按钮中的一个执行代码

[英]C# executing code from one button in another

I've one button - button1click and textbox in which when i type something and press enter, i'd like to run code from button1click. 我有一个按钮-button1click和文本框,当我键入某些内容并按Enter时,我想从button1click运行代码。

How can I do it without copying entire code from button1click into EnterPressed? 如何在不将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
    }
}

Maybe something like that? 也许是这样吗? But I'm getting errors... 但是我出错了...

void EnterPressed(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        button1click(object sender, EventArgs e)
    }
}

Just have button1_click call a method and then you can call that same method from anywhere you want to. 只需让button1_click调用一个方法,然后您就可以从任意位置调用该方法。 So in your example: 因此,在您的示例中:

private void button1click(object sender, EventArgs e)
{
       Foo();
}


void EnterPressed(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        Foo();
    }
}

void Foo()
{
    //Do Something
}

I personally wouldn't manually call another control's event. 我个人不会手动调用另一个控件的事件。

void EnterPressed(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        button1click(sender, EventArgs.Empty);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM