简体   繁体   中英

c# key press trigger button click

private void btnBrowserGo_Click(object sender, EventArgs e)
{
    browser.Navigate(txtBrowserURL.Text);
}

The code above directs the browser to the URL address in the textbox. I would like this event to also occur if the user presses the ether key when typing the URL. I have this code (below) but don't know how I would call the above code

private void txtBrowserURL_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)
    {

    }
}

You could just call the event directly using:

btnBrowserGo_Click(null, null);

However, it would be better if you didn't handle the navigation in the event itself and just called a method. That way, the method could be directly called from anywhere else in the class. This is especially useful if you have more logic in the method.

void NavigateBrowser()
{
   browser.Navigate(txtBrowserURL.Text);
}

Then, from any event, you can just call the method.

private void txtBrowserURL_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)
    {
        NavigateBrowser();
    }
}

or

private void btnBrowserGo_Click(object sender, EventArgs e)
{
    NavigateBrowser();
}

Try

btnBrowserGo_Click(null, null);

since you don't use last two parameters.

However, it might be good to extract 'logic' into some other method, and use that method from BOTH event handlers.

Your logic here is one-liner, but it might be more...

private void txtBrowserURL_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)
    {
       btnBrowserGo_Click(btnBrowserGo,EventArgs.Empty);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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