【发布时间】:2016-02-04 12:29:43
【问题描述】:
我想在RichTextBox. 中获取光标下的子字符串
private void richTextBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Clicks == 1 && e.Button == MouseButtons.Left)
{
string wholeText = richTextBox1.Text;
// Obtain the character index where the user clicks on the control.
int positionBegin = richTextBox1.GetCharIndexFromPosition(new Point(e.X, e.Y));
SelectedText = wholeText.Substring(positionBegin);
}
例如,如果我键入字符串World,然后将光标放在l 和d 之间,子字符串应该是d。到目前为止,我的代码正在运行,但是如果我将光标放在字符串的末尾,它仍然会返回 d。
我希望在这种情况下它会返回空。它看起来像一个错误。见http://www.pcreview.co.uk/forums/problem-getcharindexfromposition-t4037504.html
【问题讨论】:
-
调试确定
positionBegin的值。 -
@EvanMulawski,不,调试不起作用。好像是
GetCharIndexFromPosition的bug。 -
空白空间没有字符索引。您将需要使用 GetPositionFromCharIndex() 并查看您已关闭了多少。
-
@HansPassant,困难的部分是
GetPositionFromCharIndex()在我提到的位置返回相同的索引。 -
它不返回索引,它返回一个点。将其与鼠标位置进行比较。