I require that when the textbox text changes programmatically, the scrollbar does not move to the very top. At least how to set its coordinate programmatically and return the current position. How the TextBox property works, AutoScrollOffset is not at all clear.

My TextBox is a long list of time-varying values ​​without user input in the form of a long vertical bar. and I would like to move the scroll for example to the middle of the list and so that it remains there.

  • Very interesting question. Waiting for an answer. PS And why in the question tags "with"? - Jakeroid
  • Speaking of WPF or Forms? - ShockWave
  • talk about winforms - paul

2 answers 2

To control the ScrollBar, you can use API functions:

//Ρ‚ΠΈΠΏΡ‹ ScrollBar-ΠΎΠ² private const int SB_HORZ = 0x0; private const int SB_VERT = 0x1; //WM - сообщСния private const int WM_HSCROLL = 0x114; private const int WM_VSCROLL = 0x115; //ΠšΠΎΠΌΠΌΠ°Π½Π΄Ρ‹ для ScrollBar-Π° private const int SB_THUMBPOSITION = 4; //ΠŸΠΎΠ»ΡƒΡ‡Π΅Π½ΠΈΠΈ ΠΏΠΎΠ·ΠΈΡ†ΠΈΠΈ //Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ насколько я понял Π²Π΅Ρ€Ρ…Π½ΡŽΡŽ Π²ΠΈΠ΄ΠΈΠΌΡƒΡŽ строку TextBox-Π° //nBar = Ρ‚ΠΈΠΏ ScrollBar [DllImport("user32.dll")] private static extern int GetScrollPos(IntPtr hWnd, int nBar); //Установка ΠΏΠΎΠ·ΠΈΡ†ΠΈΠΈ Π±Π΅Π³ΡƒΠ½ΠΊΠ° Π½Π° ScrollBar-Π΅ //nBar = Ρ‚ΠΈΠΏ ScrollBar //nPos = строка [DllImport("user32.dll")] private static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw); //PostMessage, Π½Π΅ΠΎΠ±Ρ…ΠΎΠ΄ΠΈΠΌΠ° для установки ΠΏΠΎΠ·ΠΈΡ†ΠΈΠΈ Π² TextBox-Π΅ [DllImport("user32.dll")] private static extern bool PostMessageA(IntPtr hWnd, int nBar, int wParam, int lParam); //ΠŸΡ€ΠΈΠΌΠ΅Ρ€ private void test() { //ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ Π°ΠΊΡ‚ΡƒΠ°Π»ΡŒΠ½ΡƒΡŽ ΠΏΠΎΠ·ΠΈΡ†ΠΈΡŽ ScrollBar-Π° TextBox-Π° int originalLine = GetScrollPos(textBox1.Handle, SB_VERT); //Π‘Ρ‚Π°Π²ΠΈΠΌ Π±Π΅Π³ΡƒΠ½ΠΎΠΊ ScrollBar-a, Π±ΡƒΠ΄Ρ‚ΠΎ вСрхняя видимая строка Ρƒ нас восьмая SetScrollPos(textBox1.Handle, SB_VERT, 8, true); //ΠŸΡ€ΠΎΠΊΡ€ΡƒΡ‡ΠΈΠ²Π°Π΅ΠΌ TextBox ΠΊ восьмой строкС PostMessageA(textBox1.Handle, WM_VSCROLL, SB_THUMBPOSITION + 0x10000 * 8, 0); } 

Documentation:

    If you change not Text , but SelectedText , then it will scroll to the place of change. For example, you can add text and scroll to the end:

     textBox1.SelectionStart = textBox1.Text.Length; textBox1.SelectionLength = 0; textBox1.SelectedText += "ahaha haha"; 
    • it doesn’t fit, since I have a textbox for viewing, not editable, and I don’t want to place the cursor at all, so that I can scroll to the desired value and see how it changes over time. - Paul
    • one
      ok, I advise you to reflect this in question - yapycoder