Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms Textbox - Using Ctrl-Backspace to Delete Whole Word

I have a Winforms dialog that contains among other controls a TextBox that allows a single line of input. I would like to allow the user to be able to press Ctrl-Backspace to delete an entire word. This is not the default behaviour with the out-of-the-box TextBox; I get a rectangle character, rather than having the word deleted.

I have confirmed the ShortcutsEnabled property is set to True.

I did find that I can use a RichTextBox rather than a TextBox to get the behaviour I want. The problem with this is that the apperance of the RichTextBox (border in particular) is different from that of the TextBox, and I don't need or want the ability to mark up text.

So my question is how to best handle this situation? Is there some property on the TextBox that I am missing? Or is it best to use the RichTextBox, update the appearance so it is consistent, and disable markup of the text?

I am relatively happy to write the code to handle the KeyDown and KeyPress events explicity if there is no better way, but thought it was worth checking first.

like image 778
Rhys Jones Avatar asked Jul 14 '09 10:07

Rhys Jones


2 Answers

Old question, but I just stumbled upon an answer that doesn't require any extra code.

Enable autocompletion for the textbox and CTRL-Backspace should work as you want it to.

CTRL-Backspace deleting whole word to the left of the caret seems to be a 'rogue feature' of the autocomplete handler. That's why enabling autocomplete fixes this issue.

Source 1 | Source 2

--

You can enable the auto complete feature with setting the AutoCompleteMode and AutoCompleteSource to anything you like (for instance; Suggest and RecentlyUsedList)

like image 56
Damir Avatar answered Sep 22 '22 03:09

Damir


/* Update 2: Please look at https://positivetinker.com/adding-ctrl-a-and-ctrl-backspace-support-to-the-winforms-textbox-control as it fixes all issues with my simple solution */

/* Update 1: Please look also at Damir’s answer below, it’s probably a better solution :) */

I would simulate Ctrl+Backspace by sending Ctrl+Shift+Left and Backspace to the TextBox. The effect is virtually the same, and there is no need to manually process control’s text. You can achieve it using this code:

class TextBoxEx : TextBox {     protected override bool ProcessCmdKey(ref Message msg, Keys keyData)     {         if (keyData == (Keys.Control | Keys.Back))         {             SendKeys.SendWait("^+{LEFT}{BACKSPACE}");             return true;         }         return base.ProcessCmdKey(ref msg, keyData);     } } 

You can also modify the app.config file to force the SendKey class to use newer method of sending keys:

<configuration>   <appSettings>     <add key="SendKeys" value="SendInput" />   </appSettings> </configuration> 
like image 24
LukeSw Avatar answered Sep 21 '22 03:09

LukeSw