【问题标题】:Getting the caret/cursor position and keeping it at a specific spot获取插入符号/光标位置并将其保持在特定位置
【发布时间】:2012-06-14 20:02:57
【问题描述】:

我目前在一个 .NET4 Windows 窗体应用程序中。

我正在尝试制作类似智能感知的东西,但非常非常基础。

假设用户正在关注RichTextBox,并输入如下内容: Search。在这个特定的短语之后,我希望它像这样“自动填充”:Search "" 并将插入符号放在“”之间。

这样,当用户继续输入插入符号时,插入符号会保持在“”之间,如下所示:

Search "[usertypinghere][caretposition]"

我不知道如何获得插入符号的当前位置,更不用说如何保持它了。

【问题讨论】:

    标签: c# position caret autofill


    【解决方案1】:

    它是 SelectionStart 很高兴它是 TextBoxBase 的一部分,因此您可以在 TextBox、RichTextBox、MaskedTextBox 甚至其他人的自定义衍生产品中拥有它。您需要订阅 TextChanged 事件以查看“搜索”,然后在自动填充后设置 SelectionStart,然后订阅 SelectionChangedEvent 以防止 SelectionStart 偏离。

    哦,如果您有多个关键字,您需要将这些关键字组合成 Dictionary 或 Tuples 的形式,以概括这些方法。

    编辑 我的测试代码。没有闪烁,没有压倒一切的控制。只是普通的事件订阅者

    private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            if (richTextBox1.Text == "Search")
            {
                richTextBox1.Text = "Search \"\"";
                richTextBox1.SelectionStart = richTextBox1.TextLength - 1;
            }
    
        }
    
        private void richTextBox1_SelectionChanged(object sender, EventArgs e)
        {
            if (richTextBox1.Text.StartsWith("Search \"") && richTextBox1.Text.EndsWith("\""))
            {
                if (richTextBox1.SelectionStart > richTextBox1.TextLength - 1)
                {
                    richTextBox1.SelectionStart = richTextBox1.TextLength - 1;
                }
                if (richTextBox1.SelectionStart <= "Search \"".Length)
                {
                    richTextBox1.SelectionStart = "Search\"".Length+1;
                }
            }
        }
    

    【讨论】:

    • 这非常适合我愿意使用它的目的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    相关资源
    最近更新 更多