修改上Leave事件prevents tab键切换出控制的TextBox控件控件、事件、Leave、prevents

2023-09-03 16:19:22 作者:Black.

我有一个标准的TextBox控件其中我想有模仿软描述像在计算器上的标题和标签盒中。本质上,当用户的焦点进入控制,它隐藏在这种情况下的描述(用户名),并设置对齐和颜色是一个标准的文本控制。当用户离开文本框,我要检查,如果用户实际输入的任何东西,并把用户名显示备份并非如此。

I've got a standard TextBox control which I'm trying to have mimic the "soft descriptions" like those found in the title and tags boxes on StackOverflow. Essentially, when the user's focus enters the control, it hides the description ("Username") in this case, and sets alignment and color to be that of a standard text control. When the user leaves the textbox, I want to check if the user actually entered anything, and put the username display back up otherwise.

例如:

    private void tbUsername_Enter(object sender, EventArgs e)
    {
        if (tbUsername.TextAlign == HorizontalAlignment.Center)
        {
            tbUsername.TextAlign = HorizontalAlignment.Left;
            tbUsername.ForeColor = SystemColors.ControlText;
            tbUsername.Text = String.Empty;
        }
    }

    private void tbUsername_Leave(object sender, EventArgs e)
    {
        if (tbUsername.Text == String.Empty)
        {
            tbUsername.TextAlign = HorizontalAlignment.Center;
            tbUsername.ForeColor = SystemColors.InactiveCaption;
            tbUsername.Text = "Username";
        }
    }

不幸的是,当我安装这些事件,用户不能切换出该用户名的控制。控制简单地闪烁,控制返回到文本框控件本身,直到用户输入了什么东西,跳过活动身体。

Unfortunately, when I setup these events, the user cannot tab out of the username control. The control simply flickers and control returns to the textbox control itself until the user has entered something, skipping over the event body.

如果我称之为 this.SelectNextControl()事件,那么该事件进入一个无限循环。

If I call this.SelectNextControl() in the event, then the event enters an infinite loop.

是否有人看到我做错了什么?

Does anybody see what I'm doing wrong?

推荐答案

看起来像它周围的另一种方式(使用反射镜看到,它并重新聚焦回控制如果焦点在那里开始)。我认为这是一个错误,但看起来他们只是重复使用RecreateHandleCore功能重绘文本。这样的另一种方式是着重断文本框,再继续

Looks like another way around it (Using Reflector to see that it does refocus back on the Control if the focus was there to begin with). I think it is a bug, but looks like they were just reusing RecreateHandleCore function to redraw the text. So another way would be to focus off the textbox first, then continue:

  private void LeaveEvent(object sender, EventArgs e)
  {
     if (String.IsNullOrEmpty(tbUsername.Text))
     {
        tbUsername.Text = USER_NAME;
        tbUsername.ForeColor = SystemColors.InactiveCaption;
        this.Focus();
        tbUsername.TextAlign = HorizontalAlignment.Center;
     }
  }