How to scroll down in a textbox by code in C#

2019-03-10 20:43发布

I am using winforms, and I update a text box once in a while (showing messages). however, when the text reaches the end of the box it produces scrollbars and I don't know how to scroll down to the bottom. The only thing I see is ScrollToCaret, but Caret is at the beginning of the text. What is the command to scroll?

7条回答
贪生不怕死
2楼-- · 2019-03-10 21:16

C# Use Scroll Up/Down by Windows API (user32.dll)

First, we have to define a constant value:

const int EM_LINESCROLL = 0x00B6;
const int SB_HORZ = 0;
const int SB_VERT = 1;

Then, we have to declare two external methods of user32.dll:

[DllImport("user32.dll")]
static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);

Finally, use these methods to do the real thing:

SetScrollPos(myTextBox.Handle,SB_VERT,myTextBox.Lines.Length-1,true);
SendMessage(myTextBox.Handle,EM_LINESCROLL,0,myTextBox.Lines.Length-1);

Done! Simple and easy! Tested! original post

查看更多
登录 后发表回答