Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从字符索引确定逻辑行(Winforms文本框)_C#_.net_Winforms_Textbox - Fatal编程技术网

C# 从字符索引确定逻辑行(Winforms文本框)

C# 从字符索引确定逻辑行(Winforms文本框),c#,.net,winforms,textbox,C#,.net,Winforms,Textbox,如果我使用WordWrap=true在textBox中调用textBox.GetLineFromCharIndex(int),它会返回用户看到的行索引(换行数计为多行),而不是根据换行符返回的行 Line one extends to // <- word wrapped here. // <- logical line 1, GetLineFromCharIndex returns line 2 This is line two.

如果我使用
WordWrap=true
textBox
中调用
textBox.GetLineFromCharIndex(int)
,它会返回用户看到的行索引(换行数计为多行),而不是根据换行符返回的行

Line one extends to // <- word wrapped here. // <- logical line 1, GetLineFromCharIndex returns line 2 This is line two. // <- logical line 2, GetLineFromCharIndex returns line 3
第1行扩展到//查找到char索引的整个文本中出现的换行数

也许首先将文本框文本的子字符串添加到char索引。在换行符上使用拆分,并计算结果


或者,循环解决方案将使用索引函数并计算到您的char索引的换行数。

我倾向于认为此解决方案比循环查找换行更快。您需要将“”添加到包含“”消息的文本框中

[DllImport(“User32.DLL”)] 公共静态外部int SendMessage(IntPtr hWnd、UInt32 Msg、Int32 wParam、Int32 lParam); public const int EM_LINEFROMCHAR=0xC9; int noLines=SendMessage(TextBox.Handle,EM_LINEFROMCHAR,TextBox.TextLength,0); 这样,您可以根据字符串的长度找出最后一行…这将告诉您使用的逻辑行数


希望这能有所帮助,

如果不想编写循环,也可以使用字符串扩展方法wuth-Func、lambda表达式或其他任何方法-

long lineNumber = textBox.Text.Substring(0, textBox.SelectionStart).LongCount(chr => chr == '\r');

这将返回基于0的行号。

以下代码对我有效-没有明显的性能影响

this.WordWrap = false;
int lineIndex = this.GetLineFromCharIndex(this.SelectionStart);
string lineText = this.Lines[lineIndex];
this.WordWrap = true;

我在单击RichTextBox时使用此代码查找行索引:

string sub = richtextbox1.Text.Substring(0, richtextbox1.SelectionStart);
int index = sub.Count(f => f == '\n');

我最终选择了循环解决方案。谢谢@扎克:哦……我没有意识到……tbqh……这种方法在工作时很少使用。。。。很好的捕获…不幸的是,我有5000行文字,它正在“闪烁”/重新绘制大约一秒钟。。。。
string sub = richtextbox1.Text.Substring(0, richtextbox1.SelectionStart);
int index = sub.Count(f => f == '\n');