TextBox autocomplete and default buttons

2019-01-26 14:06发布

I have a .NET TextBox with AutoComplete feature on the form. The form has also AcceptButton and CancelButton defined. If I try to commit a suggestion with Enter key or close drop down with Esc, my form closes. How can I prevent this behavior?

4条回答
倾城 Initia
2楼-- · 2019-01-26 14:31

instead to Accept and Cancel buttons you can go for the following approach:

  1. Set KeyPreview property for the form to true.
  2. Handle the KeyDown event of the form, in the handler method you can have something similar to the below code

    switch (e.KeyCode)
    {
        case Keys.Enter:
        {
            if (!txtAuto.Focused)
            {
                Save();
            }
            break;
        }
        case Keys.Escape:
        {
            if (!txtAuto.Focused)
            {
                Close();
            }
            break;
        }
    }
    
查看更多
对你真心纯属浪费
3楼-- · 2019-01-26 14:35

Another option is to derive your own custom TextBox class that performs validation when Enture/Return is pressed:

public class MyTextBox : TextBox
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Enter || keyData == Keys.Return)
        {
            // Perform validation here
            return true;
        }
        else
            return false;
    }
}
查看更多
神经病院院长
4楼-- · 2019-01-26 14:45

Simple way is to remove AcceptButton and CancelButton properties while you are in auto-complete textbox:

    public Form1()
    {
        InitializeComponent();

        txtAuto.Enter +=txtAuto_Enter;
        txtAuto.Leave +=txtAuto_Leave;
    }

    private void txtAC_Enter(object sender, EventArgs e)
    {
        AcceptButton = null;
        CancelButton = null;
    }

    private void txtAC_Leave(object sender, EventArgs e)
    {
        AcceptButton = btnOk;
        CancelButton = btnCancel;
    }
查看更多
对你真心纯属浪费
5楼-- · 2019-01-26 14:57

Do not assign AcceptButton and CancelButton form properties. Set DialogResult in the buttons OnClick event.

查看更多
登录 后发表回答