简体   繁体   English

获取文本框行号

[英]Get TextBox line number

I want to get a TextBox lines number in C# winform application.我想在C# winform应用程序中获取一个TextBox行号。 But unlike this question I want the real line number, whether it is a wrapped line or is a new line with \\r\\n .但与这个问题不同的是,我想要真正的行号,无论是换行还是带有\\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: 我必须创建我自己的TextBox版本,如下所示:

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. 现在,您已将它们内置到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. 就像使用TextBox的任何属性一样使用它们并获取TextBox中显示的行数 - 如果它们是换行或实际行则无关紧要。

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我希望它有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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