简体   繁体   中英

How to get entire string at line of caret position into RichTextBox?

I'm using Visual Studio 2008 and seems that there is not CaretPosition function into richtextbox propreties. How can i get the entire rows at caret position? For example I've written this:

              show databases;
              show tables;/* (the caret (|) is flashing just here so after pressing a button i want to display "show tables"*/
              show functions; 

How can I do? Thanks in advance.

If you are using WPF :

        TextPointer caretPos = rtb.CaretPosition;
        TextPointer start=caretPos.GetLineStartPosition(0);
        TextPointer end = (caretPos.GetLineStartPosition(1) != null ? caretPos.GetLineStartPosition(1) : caretPos.DocumentEnd);

        TextRange tr = new TextRange(start, end);
        MessageBox.Show(tr.Text);

GetLineStartPosition(0) returns a TextPointer object with position the start of the current line. GetLineStartPosition(1) returns a TextPointer object with position the start of the next line.

If the caret is placed in the last line, the caretPos.GetLineStartPosition(1) will return null. You can fix this by using the caretPos.DocumentEnd .


If you are using WinForms :

        string[] lines = rtb.Lines;
        MessageBox.Show(lines[rtb.GetLineFromCharIndex(rtb.SelectionStart)]);

rtb.GetLineFromCharIndex(rtb.SelectionStart) method returns the number of the line where the caret is placed.

从.NET Framework 3.0版开始,肯定可以使用RichTextBox.CaretPosition属性。

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