Change textbox BackColor on focus in a Windows app

2019-07-24 09:24发布

问题:

In a Windows form I need to change textbox BackColor on focus. I want to do this on every textbox or control focus.

When the focus on textbox1 BackColor of this textbox should be changed and now I press tab, focus goes to next textbox (textbox2) now the BackColor of textbox2 should be changes and textbox1 BackColor should be changed back as default color.

回答1:

On textbox's event named GotFocus

Private Sub TextBox1_GotFocus(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles TextBox1.GotFocus

    textbox1.backcolor = color.red

End Sub

On textbox's event named LostFocus

Private Sub TextBox1_LostFocus(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles TextBox1.LostFocus

    textbox1.backcolor = color.white

End Sub


回答2:

Behold the C# solution:

//Properties declaration
private System.Drawing.Color NormalColor = System.Drawing.Color.FromArgb(50, 82, 110);
private System.Drawing.Color FocusColor = System.Drawing.Color.FromArgb(42, 65, 84);

// Else where in the Constructor
textBox_Username.Enter += EnterEvent;
textBox_Password.Enter += EnterEvent;
textBox_Username.Leave += LeaveEvent;
textBox_Password.Leave += LeaveEvent;

// Outside the Constructor
private void EnterEvent(object sender, EventArgs e)
{
    if (sender is TextBox)
        ((TextBox)sender).BackColor = FocusColor;
}

private void LeaveEvent(object sender, EventArgs e)
{
    if (sender is TextBox)
        ((TextBox)sender).BackColor = NormalColor;
}