C# |如何通过鼠标定位 Select TextBox 中的单词或标签?

C# | How Do I Select a Word or Tag in a TextBox by Mouse Location?

在 Windows 表单中,如果您双击文本框中的一个词,例如文本 "Do you want to play a game?",文本框会出现 selecting 一个词的异常行为,并且space 之后。

如果您想 select 文本中的标签,情况会变得更糟 "<stuff><morestuff>My Stuff</morestuff></stuff>" 如果你双击 "<stuff>" 它 selects "<stuff><morestuff>My " 可爱!

我只想 select 那些例子中的单词或标签。有什么建议吗?

我看到 DoubleClick 的 EventArgs 没有鼠标位置。 但是MouseDown确实提供了"MouseEventArgs e",它提供了e.Location。所以这就是我使用控制键和鼠标向下移动到 select 像 <stuff>.

这样的标签的方法
    private void txtPattern_MouseDown(object sender, MouseEventArgs e)
    {
        if ((ModifierKeys & Keys.Control) == Keys.Control && e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            int i = GetMouseToCursorIndex(txtPattern, e.Location);
            Point p = AreWeInATag(txtPattern.Text, i);
            txtPattern.SelectionStart = p.X;
            txtPattern.SelectionLength = p.Y - p.X;
        }
    }

    private int GetMouseToCursorIndex(TextBox ptxtThis, Point pptLocal)
    {
        int i = ptxtThis.GetCharIndexFromPosition(pptLocal);
        int iLength = ptxtThis.Text.Length;
        if (i == iLength - 1)
        {
            //see if user is past
            int iXLastChar = ptxtThis.GetPositionFromCharIndex(i).X;
            int iAvgX = iXLastChar / ptxtThis.Text.Length;
            if (pptLocal.X > iXLastChar + iAvgX)
            {
                i = i + 1;
            }
        }
        return i;
    }

    private Point AreWeInATag(string psSource, int piIndex)
    {
        //Are we in a tag?
        int i = piIndex;
        int iStart = i;
        int iEnd = i;
        //Check the position of the tags
        string sBefore = psSource.Substring(0, i);
        int iStartTag = sBefore.LastIndexOf("<");
        int iEndTag = sBefore.LastIndexOf(">");
        //Is there an open start tag before
        if (iStartTag > iEndTag)
        {
            iStart = iStartTag;
            //now check if there is an end tag after the insertion point
            iStartTag = psSource.Substring(i, psSource.Length - i).IndexOf("<");
            iEndTag = psSource.Substring(i, psSource.Length - i).IndexOf(">");
            if (iEndTag != -1 && (iEndTag < iStartTag || iStartTag == -1))
            {
                iEnd = iEndTag + i + 1;
            }
        }
        return new Point(iStart, iEnd);
    }