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.
I had problems with these approaches:
Looking at the .NET reference source what .Cut() does lead me to the following solution: Select the text in the TextBox and then use WM_CLEAR to clear it. Seems to work fine and it's not sending artificial key press events.
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
andAutoCompleteSource
to anything you like (for instance;Suggest
andRecentlyUsedList
)Regex was made for this. Use it.
DWF and giangurgolo, thanks for your information provided. Below a refined version of it. Note that it also considers
ComboBox
, as that has the very same issue asTextBox
. Also note that shortcuts are only active if configuration ofTextBox
orComboBox
allow so.TextBoxEx:
ComboxBoxEx:
String auxiliary (e.g. static class StringEx):
/* Update: 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:
You can also modify the app.config file to force the SendKey class to use newer method of sending keys:
This is what I landed up using, it also handles multi line textboxes