C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as “Ctrl+A” to get through?

后端 未结 5 1026
抹茶落季
抹茶落季 2021-02-03 22:01

Sorry for the long title, but I couldn\'t think of another way to put it.

I have this:

    private void textBoxToSubmit_KeyDown(object sender, KeyEventAr         


        
相关标签:
5条回答
  • 2021-02-03 22:30

    You can Use KeyPress instead of KeyUp or KeyDown its more efficient and here's how to handle

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                button1.PerformClick();
            }
        }
    

    hope it works

    0 讨论(0)
  • 2021-02-03 22:30

    You do not need any client side code if doing this is ASP.NET. The example below is a boostrap input box with a search button with an fontawesome icon.

    You will see that in place of using a regular < div > tag with a class of "input-group" I have used a asp:Panel. The DefaultButton property set to the id of my button, does the trick.

    In example below, after typing something in the input textbox, you just hit enter and that will result in a submit.

    <asp:Panel DefaultButton="btnblogsearch" runat="server" CssClass="input-group blogsearch">
    <asp:TextBox ID="txtSearchWords" CssClass="form-control" runat="server" Width="100%" Placeholder="Search for..."></asp:TextBox>
    <span class="input-group-btn">
        <asp:LinkButton ID="btnblogsearch" runat="server" CssClass="btn btn-default"><i class="fa fa-search"></i></asp:LinkButton>
    </span></asp:Panel>
    
    0 讨论(0)
  • 2021-02-03 22:33

    Can you not use AcceptButton in for the Forms Properties Window? This sets the default behaviour for the Enter key press, but you are still able to use other shortcuts.

    0 讨论(0)
  • 2021-02-03 22:38

    https://stackoverflow.com/a/16350929/11860907

    If you add e.SuppressKeyPress = true; as shown in the answer in this link you will suppress the annoying ding sound that occurs.

    0 讨论(0)
  • 2021-02-03 22:49

    If you want the return to trigger an action only when the user is in the textbox, you can assign the desired button the AcceptButton control, like this.

        private void textBox_Enter(object sender, EventArgs e)
        {
            ActiveForm.AcceptButton = Button1; // Button1 will be 'clicked' when user presses return
        }
    
        private void textBox_Leave(object sender, EventArgs e)
        {
            ActiveForm.AcceptButton = null; // remove "return" button behavior
        }
    
    0 讨论(0)
提交回复
热议问题