我有一个 Winforms 对话框,其中包含一个允许单行输入的 TextBox 以及其他控件.我想让用户能够按 Ctrl-Backspace 删除整个单词.这不是开箱即用 TextBox 的默认行为;我得到一个 rectangle 字符,而不是删除这个词.
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.
我已确认 ShortcutsEnabled
属性设置为 True
.
I have confirmed the ShortcutsEnabled
property is set to True
.
我确实发现我可以使用 RichTextBox 而不是 TextBox 来获得我想要的行为.这样做的问题是 RichTextBox(特别是边框)的外观与 TextBox 的不同,我不需要或不想要标记文本的能力.
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.
所以我的问题是如何最好地处理这种情况?TextBox 上是否有一些我缺少的属性?还是最好使用 RichTextBox,更新外观使其保持一致,并禁用文本标记?
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?
如果没有更好的方法,我比较乐意编写代码来显式处理 KeyDown 和 KeyPress 事件,但认为值得先检查一下.
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.
/* 更新2:请看https://positivetinker.com/adding-ctrl-a-and-ctrl-backspace-support-to-the-winforms-textbox-control 因为它用我的简单解决方案解决了所有问题 */
/* 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 */
/* 更新 1:还请看下面 Damir 的回答,这可能是一个更好的解决方案 :) */
我将通过将 Ctrl+Shift+Left 和 Backspace 发送到 TextBox 来模拟 Ctrl+Backspace.效果几乎一样,无需手动处理控件的文本.您可以使用以下代码实现它:
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);
}
}
您还可以修改 app.config 文件以强制 SendKey 类使用更新的发送密钥方法:
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>
这篇关于Winforms 文本框 - 使用 Ctrl-Backspace 删除整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!