【问题标题】:Selecting/Highlighting certain text in textbox在文本框中选择/突出显示某些文本
【发布时间】:2023-04-04 07:30:01
【问题描述】:

所以我有一个带有时间的文本框,看起来像这样;

当你点击文本框,然后点击小时部分,像这样;

应该是这样的;

几分钟也是如此,所以当你在这样的文本框的分钟部分时;

那么它应该是这样的;

基本上我要做的是让程序为您选择/突出显示时间。取决于您点击的内容。

到目前为止我尝试过的是这个;

当您“选择”小时部分时会发生什么:

textBox1.SelectionStart = 0; // The start of the selection
   textBox1.SelectionLength = 2; //Untill the ":" which seperates the hours from minutes

这行得通,文本将像第三张图片一样被选中。

这部分:

textBox1.SelectionStart = 3; // The start of the selection, in this case after the ":"
       textBox1.SelectionLength = textBox1.Text.Length; //Untill the end

我知道您应该能够为此编写一个简单的 if 语句。

但我的问题是,如何检查“光标”在文本框中的哪个部分?

【问题讨论】:

  • 总是在textBox1.SelectionStart

标签: c# winforms highlight


【解决方案1】:

通过选择开始,您可以知道光标在文本框中的位置。

private void textBox1_MouseClick(object sender, MouseEventArgs e)
            {
                if (textBox1.SelectionStart < 3)
                {
                    textBox1.SelectionStart = 0;
                    textBox1.SelectionLength = 2;
                }
                else if (textBox1.SelectionStart > 2)
                {
                    textBox1.SelectionStart = 3;
                    textBox1.SelectionLength = textBox1.Text.Length;
                }
            }

如果 if 语句为真,我将选择某个文本,例如,如果您的 SelectionStart 为 0,即位于文本框的开头,则前 2 位将突出显示。

它应该与这两个 if 语句一起使用。

【讨论】:

    猜你喜欢
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多