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:18

In WPF apps This code working perfectly

private void txt1_KeyDown(object sender, KeyEventArgs e)
  {
     if (Keyboard.IsKeyDown(Key.Enter) )
         {
              Button_Click(this, new RoutedEventArgs());
         }
   }
查看更多
Deceive 欺骗
3楼-- · 2020-05-15 23:20

there you go.

private void YurTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            YourButton_Click(this, new EventArgs());
        }
    }
查看更多
\"骚年 ilove
4楼-- · 2020-05-15 23:20

There are some cases, when textbox will not handle enter key. I think it may be when you have accept button set on form. In that case, instead of KeyDown event you should use textbox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)

查看更多
叼着烟拽天下
5楼-- · 2020-05-15 23:21

Since everybody covered the KeyDown answers, how about using the IsDefault on the button?

You can read this tip for a quick howto and what it does: http://www.codeproject.com/Tips/665886/Button-Tip-IsDefault-IsCancel-and-other-usability

查看更多
够拽才男人
6楼-- · 2020-05-15 23:22

You can handle the keydown event of your TextBox control.

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode==Keys.Enter)
    buttonSearch_Click(sender,e);
}

It works even when the button Visible property is set to false

查看更多
可以哭但决不认输i
7楼-- · 2020-05-15 23:28
    private void textbox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            //cod for run
        }
    }

    private void buttonSearch_Click(object sender, EventArgs e)
    {
        textbox1_KeyDown(sender, new KeyEventArgs(Keys.Enter));
    }
查看更多
登录 后发表回答