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

本文介绍了一个使用WinAPI实现的编辑器中同步滚动条位置的方法。通过获取和设置编辑器与行号显示区的滚动位置,确保两者始终保持同步。此外还提供了计算行数并动态更新行号显示的代码。

 

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

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JackieZhengChina

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值