【发布时间】:2019-12-12 13:59:29
【问题描述】:
我的 Windows 窗体中有多个文本框,当用户单击它们时,我希望它们的文本被选中。我试图找到一种方法,当用户在框中连续单击时,只在框中选择文本的第一次单击。我希望随后在同一个框中单击以放置文本光标框,而不是无休止地选择文本,这就是现在正在发生的事情。
我尝试在 if 语句中调用focused.Select(),该语句仅在未选择任何文本时运行,如下所示。问题在于,在用户单击所选文本短暂“取消选择”之后,Highlight_OnClick 运行并再次选择文本。
private void HighlightWhenFocused(object sender, EventArgs e)
{
if (sender is TextBox)
{
TextBox focused = sender as TextBox;
focused.Select(0, focused.Text.Length);
//if (focused.SelectionLength == 0 { focused.Select(0, focused.Text.Length); }
// does not work either
}
}
我上面的代码总是选择文本,但问题是即使用户点击了已经选择的文本框,后续点击也只会重新选择文本。
【问题讨论】:
-
处理
Enter事件,然后在事件处理程序BeginInvoke(new Action(() => ((TextBox)sender).SelectAll()));中 -
在链接的帖子中,看看this answer。