Press enter in textbox to and execute button comma

2020-05-15 22:52发布

I want to execute the code behind my Search Button by pressing Enter. I have the Accept Button property to my search button. However, when i place my button as NOT visible my search doesn't execute.

I want to be able to press Enter within my text box and execute my button while its not visible. Any suggestions would be great! Below is one attempt at my code in KeyDown Event

if (e.KeyCode == Keys.Enter)
    {
        buttonSearch_Click((object)sender, (EventArgs)e);
    }

10条回答
2楼-- · 2020-05-15 23:29

You could register to the KeyDown-Event of the Textbox, look if the pressed key is Enter and then execute the EventHandler of the button:

private void buttonTest_Click(object sender, EventArgs e)
{
    MessageBox.Show("Hello World");
}

private void textBoxTest_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        buttonTest_Click(this, new EventArgs());
    }
}
查看更多
ゆ 、 Hurt°
3楼-- · 2020-05-15 23:29

If buttonSearch has no code, and only action is to return dialog result then:

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
            DialogResult = DialogResult.OK;
    }
查看更多
贼婆χ
4楼-- · 2020-05-15 23:33

If you're just gonna click the button when Enter was pressed how about this?

private void textbox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            buttonSearch.PerformClick();
        }
查看更多
在下西门庆
5楼-- · 2020-05-15 23:34

Alternatively, you could set the .AcceptButton property of your form. Enter will automcatically create a click event.

this.AcceptButton = this.buttonSearch;
查看更多
登录 后发表回答