Search code examples
c#winformsautocompletetextboxselectall

Select all text in textbox with autocomplete (C# winforms)


I've created a textbox with autocomplete functionality, but I encounter the following problem. Whenever I press Ctrl+A to select all the text in the textbox, the text disappears.

Here is my source code for the textbox:

        this.textBox1 = new System.Windows.Forms.TextBox();
        this.textBox1.AutoCompleteCustomSource.AddRange(new string[] {
        "hello",
        "test",
        "ahha",
        "haha"});
        this.textBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
        this.textBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
        this.textBox1.Location = new System.Drawing.Point(13, 13);
        this.textBox1.Name = "textBox1";
        this.textBox1.Size = new System.Drawing.Size(100, 20);
        this.textBox1.TabIndex = 0;

I'd like the text to highlight and not disappear. Thanks in advance.


Solution

  • If I add the following code, the behavior stops:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Control | Keys.A))
        {
            SelectAll();
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
    

    but I'm still not sure why the append feature on Autocomplete mode deletes the text without overriding Ctrl+A