在Windows窗体中,如果您双击文本框中的单词,并用文本“您想玩游戏?”说,该文本框具有选择单词和其后的空格的不可思议的行为。
如果您要在文本中选择一个标签,例如"<stuff><morestuff>My Stuff</morestuff></stuff>"
如果双击"<stuff>"
它选择"<stuff><morestuff>My "
可爱!
我希望它仅选择单词或这些示例中的标签。有什么建议吗?
我看到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);
}