计算c#中statusstrip中每行(富文本框)的字符数

时间:2015-12-25 19:20:24

标签: c# .net

我几乎用c#设计了一个记事本。但我现在面临的唯一问题是我的statusstrip。

  

我的需要 - 我想显示每行的字符数。

当用户按下回车键时,它应该转到新行,现在字符数应从1开始。

技术上 - Col = 1,Ln = 1; //(最初)Col =每行字符数Ln =行数               当用户按下回车键 -               Ln = 2并继续,Col =我们在该特定行中键入的字符数 我试过这些代码 -

 private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        int count = Convert.ToInt32(e.KeyChar);
        if (Convert.ToInt32(e.KeyChar) != 13)
        {
            Col = richTextBox1.Text.Length;
            toolStripStatusLabel1.Text = "Col:" + Col.ToString() + "," + "Ln:" + Ln;
        }
        if (Convert.ToInt32(e.KeyChar) == 13)
        {
            //richTextBox1.Clear(); 
            Ln = Ln + 1;
            toolStripStatusLabel1.Text = "Col:" + Col.ToString() + "Ln:" + Ln;
        }
    }

1 个答案:

答案 0 :(得分:0)

假设您使用的是Windows窗体,则可以使用以下解决方案(但您必须订阅SelectionChanged事件而不是富文本框控件的KeyPress事件:

private void richTextBox1_SelectionChanged(object sender, EventArgs e)
{
    int currentIndex = richTextBox1.SelectionStart;

    // Get the line number of the cursor.
    Ln = richTextBox1.GetLineFromCharIndex(currentIndex);

    // Get the index of the first char in the specific line.
    int firstLineCharIndex = richTextBox1.GetFirstCharIndexFromLine(Ln);

    // Get the column number of the cursor.
    Col = currentIndex - firstLineCharIndex;

    // The found indices are 0 based, so add +1 to get the desired number.
    toolStripStatusLabel1.Text = "Col:" + (Col + 1) + "   Ln:" + (Ln + 1);
}
相关问题