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?
[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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With