首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

RichTextBox实时获取鼠标所在位置的行号和该行字符、列号,要如何做

2012-01-19 
RichTextBox实时获取鼠标所在位置的行号和该行字符、列号,要怎么做?想在RichTextBox中,实时获取鼠标所在位

RichTextBox实时获取鼠标所在位置的行号和该行字符、列号,要怎么做?
想在RichTextBox中,实时获取鼠标所在位置的行号、该行的内容、以及列号,要怎么做?
PS:不是光标所在行号,据说要用WinApi SendMessage和Marshal来做,但我没做出来。

[解决办法]
通过变通的方式解决吧,通过计算来实现!!
左上角坐标,光标处坐标,字符大小,来计算光标在哪一行,哪一列。

下面例程是在richtextbox前面加入行号,同样能确定哪一行,那一列。中文字符我没有测试过!

C# code
using System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing;using System.Data;using System.Text;using System.Windows.Forms;namespace NumberedTextBox{    public partial class NumberedTextBoxUC : UserControl    {        public NumberedTextBoxUC()        {            InitializeComponent();            numberLabel.Font = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size + 1.019f);        }        private void updateNumberLabel()        {            //得到第一个字符和第一行            Point pos = new Point(0, 0);            int firstIndex = richTextBox1.GetCharIndexFromPosition(pos);            int firstLine = richTextBox1.GetLineFromCharIndex(firstIndex);            //得到最后一个字符和最后一行            pos.X = ClientRectangle.Width;            pos.Y = ClientRectangle.Height;            int lastIndex = richTextBox1.GetCharIndexFromPosition(pos);            int lastLine = richTextBox1.GetLineFromCharIndex(lastIndex);            //这是最后一个字符的位置,我们通过Y值计算字符长度            pos = richTextBox1.GetPositionFromCharIndex(lastIndex);                       //在每一行前面加行号            numberLabel.Text = "";            for (int i = firstLine; i <= lastLine + 1; i++)            {                numberLabel.Text += i + 1 + "\n";            }        }        private void richTextBox1_TextChanged(object sender, EventArgs e)        {            updateNumberLabel();        }        private void richTextBox1_VScroll(object sender, EventArgs e)        {            int d = richTextBox1.GetPositionFromCharIndex(0).Y % (richTextBox1.Font.Height + 1);            numberLabel.Location = new Point(0, d);            updateNumberLabel();        }        private void richTextBox1_Resize(object sender, EventArgs e)        {            richTextBox1_VScroll(null, null);        }        private void richTextBox1_FontChanged(object sender, EventArgs e)        {            updateNumberLabel();            richTextBox1_VScroll(null, null);        }    }}
[解决办法]
原来写过相关的方法,后来用icsharp的editor控件去了,都忘记了
[解决办法]
1楼的代码好强,帮你顶了

热点排行