说明:通过WinApi可以准确定准滚动位置。
//行号 生成显示 这里rtbLineNum用的 RichTextBox,也可以用其它private void ShowLineNum(){rtbLineNum.Text = "";//计算行高,行数int linesLength = 0;var pFirst = tbEditor.GetPositionFromCharIndex(0);var pEnd = tbEditor.GetPositionFromCharIndex(tbEditor.Text.Length);if (pEnd.Y > pFirst.Y){var pSecondLine = tbEditor.GetPositionFromCharIndex(tbEditor.GetFirstCharIndexFromLine(1));var lineHeight = pSecondLine.Y - pFirst.Y;linesLength = (pEnd.Y - pFirst.Y) / lineHeight;}else{linesLength = 1;}//生成行数for (var i = 0; i < linesLength; i++){rtbLineNum.AppendText(i + 1 + "\n");}//行号右对齐rtbLineNum.SelectAll();rtbLineNum.SelectionAlignment = HorizontalAlignment.Right;}//上次滚动位置 行private int _scrollToLine = 0;//同步滚动private void SyncSrollLocation(){ //利用winApi 同步滚动条位置var pos = GetScrollPos(tbEditor.Handle, SB_VERT);SetScrollPos(rtbLineNum.Handle, SB_VERT, pos, true);PostMessage(rtbLineNum.Handle, WM_VSCROLL, SB_THUMBPOSITION + 0x10000 * pos, 0);}//编辑器 Resize事件private void tbEditor_Resize(object sender, EventArgs e){ShowLineNum();SyncSrollLocation();}//编辑器 TextChanged事件private void tbEditor_TextChanged(object sender, EventArgs e){ShowLineNum();SyncSrollLocation();}//编辑器 VScroll事件private void tbEditor_VScroll(object sender, EventArgs e){SyncSrollLocation();}private const int SB_VERT = 0x1;private const int WM_VSCROLL = 0x115;private const int SB_THUMBPOSITION = 4;[DllImport("user32.dll")]private static extern int SetScrollPos(IntPtr hwnd, int nBar, int nPos, bool bRedraw);[DllImport("user32.dll")]private static extern int GetScrollPos(IntPtr hwnd, int nBar);[DllImport("user32.dll")]private static extern bool PostMessage(IntPtr hWnd, int nBar, int wParam, int lParam);