powershellwinformsautocomplete

How to use textbox.AutoComplete after a specific character is typed in a Winform?


I have tried the two ways of doing this shown below, however the only time I get an autocomplete prompt is when the first character typed in the textbox matches the first character of one of the autocomplete words.

How can I have it trigger when someone types the @ symbol in the middle of characters being typed, so that an email address can be autocompleted, is this possible?

3rd

if ($tbxReminder.Text.IndexOf('@') -ge 0)
        {
            Write-Host "@ symbol";
            $autocomplete = New-Object System.Windows.Forms.AutoCompleteStringCollection;
            $tbxReminder.AutoCompleteSource = "CustomSource";
            $tbxReminder.AutoCompleteMode = "SuggestAppend";
            $autocomplete.AddRange(@("*@test.com", "apple", "banana", "cherry", "date"))
            $tbxReminder.AutoCompleteCustomSource = $autocomplete;
        }

2nd

$tbxReminder_TextChanged = {
    $typedText = $tbxReminder.Text;
    $lastChar = $typedText.Remove(0, $typedText.Length - 1);
    if ($lastChar -eq "@")
    {
        Write-Host "@ symbol";
        $autocomplete.AddRange(@("*@test.com", "apple", "banana", "cherry", "date"))
        $tbxReminder.AutoCompleteCustomSource = $autocomplete
    }
    else
    {
        $tbxReminder.AutoCompleteCustomSource = $null;
    }
}

1st

$tbxReminder.Location = (New-Object -TypeName System.Drawing.Point -ArgumentList @([System.Int32]12,[System.Int32]70))
$tbxReminder.Name = [System.String]'tbxReminder'
$tbxReminder.Size = (New-Object -TypeName System.Drawing.Size -ArgumentList @([System.Int32]220,[System.Int32]21))
$tbxReminder.TabIndex = [System.Int32]2
$tbxReminder.add_TextChanged($tbxReminder_TextChanged)
$tbxReminder.AutoCompleteSource = "CustomSource";
$tbxReminder.AutoCompleteMode = "SuggestAppend";
$autocomplete.AddRange(@("*@test.com", "apple", "banana", "cherry", "date"));

Solution

  • Here is how I implemented it in case anyone has a similar situation. If you had more than one domain for my example, I imagine you could add the range portion of autocomplete to that, I don't have code for that because I don't need that at this point.

    $tbxReminder_TextChanged = {
    
            $typedText = $tbxReminder.Text;
            $typedTextLength = $typedText.Length;
            if ($tbxReminder.Text[$typedTextLength - 1] -eq '@')
            {
                $tbxReminder.Text += "test.com";
                $tbxReminder.AcceptsTab = $true;
                $tbxReminder.SelectionStart = ($typedTextLength);
                $tbxReminder.SelectionLength = 8;
            }
        }