当C#WinForms文本框接收到焦点时,我希望它的行为类似于浏览器的地址栏.

要了解我的意思,请单击web浏览器的地址栏.您会注意到以下行为:

  1. 如果文本框之前没有聚焦,点击文本框应该 Select 所有文本.
  2. 在文本框中按下鼠标并拖动应该只 Select 我用鼠标突出显示的文本.
  3. 如果文本框已经聚焦,单击不会 Select 所有文本.
  4. 以编程方式或通过键盘Tab键聚焦文本框应 Select 所有文本.

我想在WinForms中做到这一点.

FASTEST GUN ALERT: please read the following before answering!谢谢,伙计们.:-)

Calling .SelectAll() during the .Enter or .GotFocus events won't work因为如果用户点击

Calling .SelectAll() during the .Click event won't work,因为用户不能用鼠标 Select 任何文本;.SelectAll()调用将不断覆盖用户的文本 Select .

Calling BeginInvoke((Action)textbox.SelectAll) on focus/enter event enter doesn't work因为它违反了上面的规则2,所以它将一直覆盖用户在焦点上的 Select .

推荐答案

首先,谢谢你的回答!共9个答案.非常感谢.

坏消息:所有答案都有一些怪癖,或者不太正确(或者根本不正确).我给你的每一篇帖子都加了一条 comments .

好消息:我找到了一种方法让它工作.这个解决方案非常简单,似乎适用于所有场景(鼠标向下移动、 Select 文本、标记焦点等)

bool alreadyFocused;

...

textBox1.GotFocus += textBox1_GotFocus;
textBox1.MouseUp += textBox1_MouseUp;
textBox1.Leave += textBox1_Leave;

...

void textBox1_Leave(object sender, EventArgs e)
{
    alreadyFocused = false;
}


void textBox1_GotFocus(object sender, EventArgs e)
{
    // Select all text only if the mouse isn't down.
    // This makes tabbing to the textbox give focus.
    if (MouseButtons == MouseButtons.None)
    {
        this.textBox1.SelectAll();
        alreadyFocused = true;
    }
}

void textBox1_MouseUp(object sender, MouseEventArgs e)
{
    // Web browsers like Google Chrome select the text on mouse up.
    // They only do it if the textbox isn't already focused,
    // and if the user hasn't selected all text.
    if (!alreadyFocused && this.textBox1.SelectionLength == 0)
    {
        alreadyFocused = true;
        this.textBox1.SelectAll();
    }
}

据我所知,这会导致文本框的行为与web浏览器的地址栏完全相同.

希望这能帮助下一个试图解决这个看似简单的问题的人.

再次感谢你们的回答,帮助我走上正确的道路.

.net相关问答推荐

如何将多个安装程序Bundle 到一个安装程序中?

在 Inno Setup 中判断给定服务的依赖服务

使用 PEM 文件创建 DSA 签名

为什么这两个比较有不同的结果?

使用字典作为数据源绑定组合框

maxRequestLength 的最大值?

比较 C# 中的双精度值

Style 和 ControlTemplate 的区别

比较 C# 中的字符串和对象

BackgroundWorker 中未处理的异常

HttpClient 和使用代理 - 不断得到 407

如何判断对象是否是某种类型的数组?

什么是 SUT,它来自哪里?

如何在 C# 7 中返回多个值?

什么版本的 .NET 附带什么版本的 Windows?

我们应该总是在类中包含一个默认构造函数吗?

是否有可用的 WPF 备忘单?

ILookup 接口与 IDictionary

无法使用 Unity 将依赖项注入 ASP.NET Web API 控制器

如何在 Dapper.Net 中编写一对多查询?