WinForms Textbox Autocomplete events

2019-07-07 07:03发布

问题:

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.

My idea is to create my custom textbox inheriting from TexBox and capture Enter key and the Escape key, but only when the autocomplete UI is visible. How could I know when the autocomplete list is visible?

public class MyTextBox : TextBox
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (IsOnAutoComplete())
        {
            if (keyData == Keys.Enter || keyData == Keys.Return)
            {
                return true;
            }
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

In other words, do you know how could I implement IsOnAutoComplete() method? Has the textbox any events to notice this?

Any other solution would be appreciated. Thanks in advance.

回答1:

A simple solution I have used in the past is removing the Accept and Cancel button associations when the text box has focus.

    textBox1.Enter += (o, args) =>
                                    {
                                        AcceptButton = null;
                                        CancelButton = null;
                                    };
    textBox1.Leave += (o, args) =>
                                    {
                                        AcceptButton = btnOK;
                                        CancelButton = btnCancel;
                                    };