?
說明:通過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);
?