如何从 RichTextBox 中的鼠标单击点获取插入符号位置? [英] How to get the Caret Position from mouse clicking point in a RichTextBox?

查看:34
本文介绍了如何从 RichTextBox 中的鼠标单击点获取插入符号位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 RichTextBox 文本的插入位置更改为鼠标单击位置.我使用内置方法 GetPositionFromPointWPF RichTextBox 中做到了.
但是我在 WinForms RichTextBox 中找不到任何这样的方法.

I need to change the caret position of RichTextBox text to mouse clicking position. I did it in a WPF RichTextBox by using the built-in method GetPositionFromPoint.
But I can't find any methods like this in a WinForms RichTextBox.

谁能告诉我,有没有可能让它在 Windows 窗体中工作?

Can anyone please let me know, is there any possibilites to make it work in Windows Forms?

推荐答案

单击 RichTextBox 控件的 Text 内容时,插入符号位置移动到控件内鼠标指针的位置.这个位置现在是当前的插入点.
插入符号新位置可以通过两种方式检索:

When clicking the Text content of a RichTextBox control, the caret position is moved to the position of the Mouse Pointer inside the control. This position is now the current insertion point.
The caret new position can be retrieved in two ways:

检查 SelectionStart属性:

int CaretPosition = richTextBox1.SelectionStart;

使用 MouseEventArgs 返回的鼠标指针位置 e.Location.
在这种情况下,您可以使用 GetCharIndexFromPosition 方法:

Using the Mouse Pointer position returned by the MouseEventArgs e.Location.
You can use, in this case, the GetCharIndexFromPosition method:

int CaretPosition = richTextBox1.GetCharIndexFromPosition(e.Location);

如果将 SelectionStartGetCharIndexFromPosition 返回的值进行比较,则可以验证这些值是否相等.

If you compare the values returned by SelectionStart an GetCharIndexFromPosition, you can verify that these values are equal.

如果您希望 Caret 在鼠标指针在 RichTextBox 的边界内移动时跟随鼠标指针,您可以订阅 MouseMove 事件并使用此方法将鼠标指针位置转换为字符索引位置(您需要先在 RichTextBox 控件内单击):

If you want the Caret to follow the Mouse Pointer when it moves inside the Bounds of a RichTextBox, you can then subscribe to the MouseMove event and use this method to translate the Mouse Pointer position to a char index position (you need to first click inside a RichTextBox control):

private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
    RichTextBox rtb = sender as RichTextBox;
    rtb.SelectionStart = rtb.GetCharIndexFromPosition(e.Location);
}

行位置由 返回GetLineFromCharIndex 方法:
(Lines 数组指的是由换行符分隔的文本部分(RichTextBox 中的\n)

The Line position is returned by the GetLineFromCharIndex method:
(The Lines array refers to the text parts separated by a line feed (\n in a RichTextBox)

int CaretPositionLine = richTextBox1.GetLineFromCharIndex(CaretPosition);

这篇关于如何从 RichTextBox 中的鼠标单击点获取插入符号位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆