Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`ScrollToCaret` scrolls to the end of the selected text, how can I scroll to the begining of it?

I am trying to make the selected text visible in a text box control after I found the text via a search box.

I tried the following code:

String searchText = "multiple lines of text.";
int position = textBox.Text.IndexOf(searchText);
textBox.SelectionStart = position;
textBox.SelectionLength = searchText.Length;
textBox.ScrollToCaret(); // caret is at the end of the selected text

ScrollToCaret method scrolls to the end of the selected text or the last line of the selected text. So if it spans to multiple lines and the height of this part is bigger than the height of textbox, part of the selected text may remain invisible.

Please notice I can't set the caret to the selection start too because I will loose highlight on the selected text.

How can I make sure the selected text is visible or in other words scroll to the first line of the selected text while keeping it highlighted?

like image 407
Ahmad Avatar asked Oct 30 '14 13:10

Ahmad


1 Answers

[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);    

int numLines = textBox1.GetLineFromCharIndex(textBox1.SelectionStart);
//scroll to top
SendMessage(textBox1.Handle, 0x115, 6, 0); //WM_VSCROLL
//scroll numLines
SendMessage(textBox1.Handle, 0xB6, 0, numLines); //EM_LINESCROLL