Amit Rajput
Amit Rajput

Reputation: 137

Change textbox BackColor on focus in a Windows application

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.

Upvotes: 2

Views: 3912

Answers (2)

Serge Kishiko
Serge Kishiko

Reputation: 486

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;
}

Upvotes: 1

John Woo
John Woo

Reputation: 263723

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

Upvotes: 0

Related Questions