Reputation: 12027
I've checked the other questions in SO for timeout in C#, but since I'm a beginner, I don't really know how to implement them into my code. They look too sophisticated.
I have a text box and I added a click event. Upon click, user copies the content of the text box to the clipboard. To make the copy process noticeable to the user, I change the back color of the text box. Once the content is copied, I want to change the back color of the text box back to normal. So I need to set a timeout.
private void IDBox_Click(object sender, EventArgs e)
{
CopyToClipboard((TextBox)sender);
}
private void CopyToClipboard(TextBox textBox)
{
if (textBox.Text != "")
{
textBox.BackColor = System.Drawing.Color.MistyRose;
Clipboard.SetText(textBox.Text);
// set 200ms timeout and then change BackColor
//textBox.BackColor = System.Drawing.SystemColors.Window;
}
}
How can I set a timeout? An example would be great.
Upvotes: 2
Views: 4099
Reputation: 421
Supposed you have a textbox named test you can use the dispatcher timer in WPF or the Windows forms timer if you are working in windows forms.
test.Background = new SolidColorBrush(Colors.MistyRose);
Clipboard.SetText(test.Text);
var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler((s, x) =>
{
dispatcherTimer.Stop();
test.Background = new SolidColorBrush(Colors.White);
});
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 200);
dispatcherTimer.Start();
Upvotes: 1
Reputation: 8194
Use a Timer
and change colour back in the Elapsed
event.
Quick and dirty (untested) code to get you started:
private void CopyToClipboard(TextBox textBox)
{
if (textBox.Text != "")
{
textBox.BackColor = System.Drawing.Color.MistyRose;
Clipboard.SetText(textBox.Text);
// Create a timer with a 1 second interval.
System.Timers.Timer aTimer = new System.Timers.Timer(1000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
// Only tick one time
aTimer.AutoReset = false;
// Start timer
aTimer.Enabled = true;
}
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate
{
textBox.BackColor = System.Drawing.SystemColors.Window;
});
}
Upvotes: 2
Reputation: 21979
Not sure if that fits to your requirements (beginner?), but that will do a simple blinking by using Task
and invoking text color changing back after delay:
textBox.BackColor = Color.MistyRose;
Task.Run(() =>
{
Thread.Sleep(200); // delay
this.BeginInvoke((MethodInvoker)delegate
{
textBox.BackColor = SystemColors.Window;
});
});
Upvotes: 2