简体   繁体   中英

counting number of characters per each line(rich textbox) in statusstrip in c#

I have almost designed a notepad using c#. But only problem I'm facing now is in my statusstrip.

My need- I want to display character count per each line.

When user press enter key it should come to new line and now character count should start from 1.

Technically - Col=1, Ln=1; //(initially)Col=no of character per line Ln=line count When user press enter key- Ln=2 and goes on and Col=No of characters we have typed in that specific line I've tried these lines of code -

 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;
        }
    }

Supposing you are using Windows Forms, you can use the following solution (but you have to subscribe to the SelectionChanged event instead of the KeyPress event of the rich text box control):

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM