Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Label visible for 5 seconds in winforms

I am creating a WinForms application in visual studio 2017.

I have a Login form where, if the user enters a wrong username or password, a label that has the property visible = false, becomes visible for 5 seconds and the goes back for being not visible.

I have tried to do something like this:

label3.Visible = true;
Thread.Sleep(3000);
label3.Visible = false;

Obviously, this doesn't work, I couldn' find anyone with a very similar problem online, so I hope you could help me with this.

I have seen other soloutions using this:

var t = new Timer();
t.Interval = 3000; // it will Tick in 3 seconds
t.Tick += (s, e) =>
{
    label3.Hide();
    t.Stop();
};
t.Start();

but I get an error saying "a local or parameter named 'e' cannot be declared in this scope because that name is used in an enclosing local scope to define a local parameter".

like image 850
Omar AlMadani Avatar asked Nov 25 '25 13:11

Omar AlMadani


2 Answers

if you're using .NET Framework 4.5 or above, you can also have done it with this code:

label3.Visible = true;
System.Threading.Tasks.Task.Delay(3000).ContinueWith(_ =>
{
    Invoke(new MethodInvoker(()=> { label3.Visible = false; }));
});
like image 68
Tiber Septim Avatar answered Nov 28 '25 04:11

Tiber Septim


Rename e to some other variable as the error says you are already having a local variable named e in the scope.

var t = new Timer();
t.Interval = 3000; // it will Tick in 3 seconds
t.Tick += (s, event) =>
{
    label3.Hide();
    t.Stop();
};
t.Start();
like image 29
Ipsit Gaur Avatar answered Nov 28 '25 02:11

Ipsit Gaur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!