Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

c# - TextBox Autocompletion - Prevent automatic submit(Keydown with Keycode.Enter) when clicking suggested item

Hello I've a TextBox with Autocompletion source & mode set up in a winform. Now i've the problem that with clicking a suggestion, it will also trigger KeyDown event with Keycode.Enter, leading into weird behavior.

Can i somehow prevent to trigger the event at all when clicking a suggestion from autocomplete dropdown?

Currently in the keydown event i check if the autocomplete source contains what is written into the textbox, but with this, a user also can't submit anymore by enter if he just wants to send the suggested text anyway.

private void tbInput_KeyDown(object sender, KeyEventArgs e)
    {

        if (e.Control && e.KeyCode == Keys.A)
        {
            e.SuppressKeyPress = true;
            tbInput.SelectAll();
        }


        if (e.KeyCode == Keys.Enter)
        {
            e.SuppressKeyPress = true;
            if (tbInput.AutoCompleteCustomSource.Contains(tbInput.Text) && tbInput.Text.EndsWith(" "))
            {
                tbInput.SelectionStart = tbInput.Text.Length;
                return;
            }
            btnSend_Click(sender, null);
        }
    }

What i did here is, that autocompletesource entries with a space at the end (awaiting a parameter) will not send. Others will send anyway. But i want none to send without the user confirming the selected suggestion, while keeping the general logic to send commands by pressing Enter.

//EDIT
I've added a github repo for testing: https://github.com/WaGi-Coding/AutocompleteIssue

// Solved by comment from Jimi
Also when autocomplete appends & i press Ctrl+A, it will delete all text, instead of selecting everything. Thats only the case if you continue on from the appended text, if you add 1 more character, delete it again and press Ctrl+A, it behaves like expected. But the bigger problem for me is the first issue above. //////////////////////////////

Should i use some library instead? Is there some better way to modify how it behaves?

Any help would be appreciated. Greetings

question from:https://stackoverflow.com/questions/65909805/textbox-autocompletion-prevent-automatic-submitkeydown-with-keycode-enter-wh

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...