C# RichTextBox 做简单的HTML代码编辑器 ---------利用WinApi修正左侧显示行号 误差

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/admans/article/details/81585503

说明:通过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);

猜你喜欢

转载自blog.csdn.net/admans/article/details/81585503