Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinForms Textbox Autocomplete events

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.

like image 785
Daniel Peñalba Avatar asked Apr 13 '26 10:04

Daniel Peñalba


1 Answers

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;
                                    };
like image 109
John Arlen Avatar answered Apr 14 '26 22:04

John Arlen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!