为什么我的richtextbox不能更改颜色?

时间:2020-06-23 19:37:07

标签: c# forms colors richtextbox

我正在尝试为我的子网计算器为Richtextbox中的字母提供不同的颜色,但是Richtextbox直到第26个字母时才更改颜色。

外观:

How it looks

        int iValueSm = trackBarSmMask.Value;
        rtbScroll.Text = "";
        rtbScroll.SelectionStart = rtbScroll.TextLength;
        rtbScroll.SelectionLength = 0;

        for (int i = 1; i <= iValueSm; i++)
        {
            rtbScroll.SelectionColor = Color.Blue;
            rtbScroll.AppendText("N");              

            if (i%8==0 && i != 32)
            {
                rtbScroll.Text = rtbScroll.Text + "."; 
            }
        }

        for (int i = iValueSm+1; i <= 32; i++)
        {
            rtbScroll.SelectionColor = Color.Red;
            rtbScroll.AppendText("H");              

            if (i % 8 == 0 && i != 32)
            {
                rtbScroll.Text = rtbScroll.Text + ".";
            }
        }

        labelAmountNetID.Text = "/" + iValueSm.ToString();

2 个答案:

答案 0 :(得分:1)

无论何时设置.Text()属性,都将所有格式重置为黑白。

这是我如何使用SelectedText编写它的方法:

enter image description here

private void Form1_Load(object sender, EventArgs e)
{
    updateRTB();
}

private void trackBarSmMask_ValueChanged(object sender, EventArgs e)
{
    updateRTB();
}

private void trackBarSmMask_Scroll(object sender, EventArgs e)
{
    updateRTB();
}

private void updateRTB()
{            
    rtbScroll.Text = "";
    rtbScroll.SelectionStart = 0;
    rtbScroll.SelectionLength = 0;
    int iValueSm = trackBarSmMask.Value;
    labelAmountNetID.Text = "/" + iValueSm.ToString();
    for (int i = 1; i <= 32; i++)
    {
        rtbScroll.SelectionColor = (i <= iValueSm) ? Color.Blue : Color.Red;
        rtbScroll.SelectedText = (i <= iValueSm) ? "N" : "H";
        if (i % 8 == 0 && i != 32)
        {
            rtbScroll.SelectionColor = Color.Black;
            rtbScroll.SelectedText = ".";
        }
    }
}

答案 1 :(得分:1)

好吧,有很多方法可以解决这个问题,但这是一个建议:

// Track bar definitions...
 private void SetTrackBarVals()
 {
     trackBar1.Minimum = 0;
     trackBar1.Maximum = 31;
 }

 private void trackBar1_Scroll(object sender, EventArgs e)
 {
     var counter = 0;
     var dotsCounter = 0;
     rtbScroll.Text = "";
     int iValueSm = trackBar1.Value + 1; // +1 because we start counting from 0

     for (int i = 1; i <= 32; i++)
     {
         if (counter > 0 && counter % 8 == 0)
         {
             // new octet
             rtbScroll.AppendText(".");
             dotsCounter++;
         }

         if (i > iValueSm)
         {
             // It is red
             rtbScroll.AppendText("H");
             rtbScroll.SelectionStart = (i - 1) + dotsCounter;
             rtbScroll.SelectionLength = 1 ;
             rtbScroll.SelectionColor = Color.Red;
         }
         else
         {
             rtbScroll.AppendText("N");
         }

         counter++;
     } 
 }
相关问题