【问题标题】:C# | How Do I Select a Word or Tag in a TextBox by Mouse Location?C# |如何通过鼠标位置在文本框中选择单词或标签?
【发布时间】:2015-01-28 21:09:26
【问题描述】:

在 Windows 窗体中,如果您双击文本框中的某个单词,并说“你想玩游戏吗?”,文本框会出现选择单词及其后空格的奇怪行为。

如果你想在文本中选择一个标签,情况会变得更糟 "<stuff><morestuff>My Stuff</morestuff></stuff>" 如果你双击 "<stuff>" 它选择 "<stuff><morestuff>My " 可爱!

我希望它只选择单词或这些示例中的标签。有什么建议吗?

【问题讨论】:

  • 您是否尝试过监听双击事件并在触发后通过编码选择所需的文本?

标签: c# winforms textbox tags selection


【解决方案1】:

我看到 DoubleClick 的 EventArgs 没有鼠标位置。 但是 MouseDown 确实提供了“MouseEventArgs e”,它提供了 e.Location。所以这就是我想出的使用控制键和鼠标向下选择像<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);
    }

【讨论】:

  • I see that DoubleClick's EventArgs does not have a mouse position 但您始终可以通过Control.MousePosition 获取屏幕坐标中的鼠标位置,然后在文本框上调用PointToClient 以获取相对于文本框边界的位置。
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 2014-06-24
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
相关资源
最近更新 更多