【问题标题】:Implement textbox shortcuts [duplicate]实现文本框快捷方式[重复]
【发布时间】:2013-11-14 12:47:18
【问题描述】:

我在我的项目中使用来自Qios DevSuite 的名为QTextBox 的组件。

类似于 .NET TextBox 中默认发生的情况,当用户在键入时按下 Control+Backspace,而不是删除光标左侧的单词, 而是插入字符 ''。

为了解决这个问题,我想我会做类似的事情

public class QTextBoxEx : QTextBox
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Control | Keys.Back))
        {
            // here goes my word removal code
            return true;
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }
}

这是一个好方法还是已经有一个 .NET 内置系统来实现这种行为?另外,从搜索字符串中删除最后一个单词的“最干净”的方法是什么? (我现在可以想到 string.Replace 和 Regex)

【问题讨论】:

  • Qios 是否适用于 Win 表单?
  • 是的。我添加了标签 winforms。

标签: c# .net winforms textbox


【解决方案1】:
public class QTextBoxEx : QTextBox
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        // shortcut to search bar
        if (keyData == (Keys.Control | Keys.Back))
        {
            // 1st scenario: some text is already selected. 
            // In this case, delete only selected text. 
            if (SelectedText != "")
            {
                int selStart = SelectionStart;
                Text = Text.Substring(0, selStart) + 
                    Text.Substring(selStart + SelectedText.Length);

                SelectionStart = selStart;
                return true;
            }

            // 2nd scenario: delete word. 
            // 2 steps - delete "junk" and delete word.

            // a) delete "junk" - non text/number characters until 
            // one letter/number is found
            for (int i = this.SelectionStart - 1; i >= 0; i--)
            {
                if (char.IsLetterOrDigit(Text, i) == false)
                {
                    Text = Text.Remove(i, 1);
                    SelectionStart = i;
                }
                else
                {
                    break;
                }
            }

            // delete word
            for (int i = this.SelectionStart - 1; i >= 0; i--)
            {
                if (char.IsLetterOrDigit(Text, i))
                {
                    Text = Text.Remove(i, 1);
                    SelectionStart = i;
                }
                else
                {
                    break;
                }
            }
            return true;
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }
}

这段代码假设了两种不同的场景:

  • 已选择文本:仅删除选定文本。
  • 没有选定的文本:单词被删除。

【讨论】:

    猜你喜欢
    • 2013-09-27
    • 2016-07-06
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    相关资源
    最近更新 更多