【问题标题】:C# Window From Autoselects Text来自自动选择文本的 C# 窗口
【发布时间】:2019-08-09 23:16:43
【问题描述】:

很久没有接触过WinForms了。

现在我被一些琐碎的事情困住了,但无法弄清楚。

我有一个 Winform,当发生 Timer Tick 时,我想在新表单消息框中显示一条消息:

 frmMessage frmM = new frmMessage();
 frmM.txtMessage.Text =  ConfigurationSettings.AppSettings["Message"];
 frmM.Show();

它可以工作,但文本框中的文本显示为选中(蓝色背景)。

我试过了

txtMessage.SelectionLength = 0;

没有帮助。

还尝试将焦点设置到不同的控件,也没有帮助。

现在,作为一种解决方法,我将使用标签。

【问题讨论】:

  • 您在哪里调用线路将 SelectionLength 设置为零?在 frmM.Show 行之前还是之后?
  • @Steve 在 Load 事件和 Tick 事件上。
  • 尝试使用 Shown 事件
  • 两种形式,但没有帮助。

标签: c# winforms


【解决方案1】:

这是 TextBox 类实现方式的结果。如果未专门设置选择,则控件获得焦点时将选择所有文本。

来自TextBox.OnGotFocus

Protected override void OnGotFocus(EventArgs e) {
          base.OnGotFocus(e);
          If (!selectionSet) {
              // We get one shot at selecting when we first get focus.  If we don't
              // do it, we still want to act Like the selection was set.
              selectionSet = true;

              // If the user didn't provide a selection, force one in.
              If (SelectionLength == 0 && Control.MouseButtons == MouseButtons.None) {
                  SelectAll();
              }
          }

另外,由于SelectionLength Property 的实现方式,将该属性设置为零不会设置 selectionSet` 标志,因为它已经为零。

相反,设置文本后立即设置 TextBox.SelectionStart 属性,因为这将设置该标志。

txtMessage.SelectionStart = 0;

但是,使用Label 显示消息的工作循环比使用输入控件更合适。

【讨论】:

    【解决方案2】:

    这不是最好的答案,但它有效。你可以试试这个

    frmMessage frmM = new frmMessage();
    frmM.txtMessage.Text = "";
    frmM.txtMessage.AppendText(ConfigurationSettings.AppSettings["Message"]);
    frmM.Show();
    

    【讨论】:

      猜你喜欢
      • 2015-09-23
      • 1970-01-01
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多