简体   繁体   中英

Get TextBox line number

I want to get a TextBox lines number in C# winform application. But unlike this question I want the real line number, whether it is a wrapped line or is a new line with \\r\\n .

var lines = tb.Lines.Count(); will just get the lines number with carriage return.

So How can I get what I'm looking for?

So I found my answer here

I have to create my own TextBox version like this:

using System;
using System.Windows.Forms;

namespace TextBoxLines
{
    public class TextBoxEx : TextBox
    {
        private const int EM_GETLINECOUNT = 0xBA;
        private const int EM_LINEINDEX = 0xBB;
        private const int EM_LINELENGTH = 0xC1;

        public TextBoxEx() :base()
        {
            //Since we'll want multiple lines allowed we'll add that to the constructor
            this.Multiline = true;
            this.ScrollBars = ScrollBars.Vertical;
        }

        public int LineCount
        {
            get
            {
                Message msg = Message.Create(this.Handle, EM_GETLINECOUNT, IntPtr.Zero, IntPtr.Zero);
                base.DefWndProc(ref msg);
                return msg.Result.ToInt32();
            }
        }

        public int LineIndex(int Index)
        {
            Message msg = Message.Create(this.Handle, EM_LINEINDEX, (IntPtr)Index, IntPtr.Zero);
            base.DefWndProc(ref msg);
            return msg.Result.ToInt32();
        }

        public int LineLength(int Index)
        {
            Message msg = Message.Create(this.Handle, EM_LINELENGTH, (IntPtr)Index, IntPtr.Zero);
            base.DefWndProc(ref msg);
            return msg.Result.ToInt32();
        }
    }
}

Just beautiful. Now you have them built into the TextBox. Use them just as you would use any property for the TextBox and get the number of lines displayed in the TextBox - doesn't matter if they are wrapped lines or actual lines.

I dont understand what you want, but generally you can use this code to count lines in your textbox:

public int LineNumber()
    {
        int LineNumber;
        LineNumber = textBoxNotePad.Lines.Length;
        return LineNumber;
    }

I hope it's useful

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