C# RichTextBox 做简单的HTML代码编辑器 ---------利用WinApi修正左侧显示行号 误差
生活随笔
收集整理的這篇文章主要介紹了
C# RichTextBox 做简单的HTML代码编辑器 ---------利用WinApi修正左侧显示行号 误差
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
說明:通過WinApi可以準(zhǔn)確定準(zhǔn)滾動(dòng)位置。
//行號(hào) 生成顯示 這里rtbLineNum用的 RichTextBox,也可以用其它private void ShowLineNum(){rtbLineNum.Text = "";//計(jì)算行高,行數(shù)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;}//生成行數(shù)for (var i = 0; i < linesLength; i++){rtbLineNum.AppendText(i + 1 + "\n");}//行號(hào)右對(duì)齊rtbLineNum.SelectAll();rtbLineNum.SelectionAlignment = HorizontalAlignment.Right;}//上次滾動(dòng)位置 行private int _scrollToLine = 0;//同步滾動(dòng)private void SyncSrollLocation(){ //利用winApi 同步滾動(dòng)條位置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);?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的C# RichTextBox 做简单的HTML代码编辑器 ---------利用WinApi修正左侧显示行号 误差的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# RichTextBox 做简单的H
- 下一篇: C# 扩展object类 将string