Search code examples
c#winformstextbox

Windows forms textbox font color change for a limited time


I am new to C# and Windows Forms, but here is a thing: I wanna change text color in my textbox named NameField to red if my boolean function returns false;

I tried using NameField.ForeColor = System.Drawing.Color.Red; but it changes it forever to red, but I want just for a few seconds. Is it possible?


Solution

  • The simplest way is to use Task.Delay. Assuming you want to do this when a button is clicked:

    private async void button1_Click(object sender, EventArgs e){
        try{
            NameField.ForeColor = System.Drawing.Color.Red;
            await Task.Delay(1000); // 1s
            NameField.ForeColor = System.Drawing.Color.Blue;
        }
         catch(Exception e){
              // handle exception
          }
    }
    

    A timer is another alternative, but then you would need to disable the timer in the event handler if you only want it to trigger once. Task.Delay does more or less the same thing, but is a bit neater.

    Keep in mind the try/catch, whenever you use async void you want to catch any exceptions to ensure that they are not lost.

    You might also want to consider repeated button presses. Either disable the button, or increment some field, and only reset the color if the field has the same value as when you set the color.