Set simple timeout - c#

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.

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

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

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();

Related

How to implement Timer Elapsed Event on UserInterface thread in Xamarin Android

Am implementing a System Timer on Xamarin Android and i have a problem with the elapsed event not raising a dialog box with the message "Time is up" when the countdown is Over...
I figured the problem might be not implementing the event on the User Interface thread so i need your help accomplishing that...
Here is my code for the Timer
class SecondActivity : AppCompatActivity
{
int counter = 10;
private System.Timers.Timer _timer;
private int _countSeconds;
protected override void OnCreate(Bundle savedInstanceState)
{
_timer = new System.Timers.Timer();
//Trigger event every second
_timer.Interval = 1000;
_timer.Elapsed += OnTimedEvent;
//count down 5 seconds
_timer.Enabled = true;
_countSeconds = 5;
}
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
_countSeconds--;
if (_countSeconds == 0) {
_timer.Stop();
Switch switch1 = this.FindViewById<Switch>(Resource.Id.switch2);
Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
Android.App.AlertDialog alert = dialog.Create();
alert.SetTitle("");
alert.SetMessage("Simple Alert");
alert.SetButton("OK", (c, ev) =>
{
// Ok button click task
});
switch1.Checked = false;
}
I just want the Elapsed event handler to display an alert dialog box when the variable count down equals zero, Thank You
After the first comment pointed me to a related question i found the method to implement the user thread and it now works as intended to display the alert dialog...
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
//This is how to make the Timer callback on the UI
RunOnUiThread(() =>
{
_countSeconds--;
if (_countSeconds == 0)
{
Switch switch1 = this.FindViewById<Switch>(Resource.Id.switch2);
Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
Android.App.AlertDialog alert = dialog.Create();
alert.SetTitle("Its over");
alert.SetMessage("Simple Alert");
alert.SetButton("OK", (c, ev) =>
{
// Ok button click task
});
alert.Show();
switch1.Checked = true;
}
});
}

Stopping focus changed event being handled multiple times in one second

I have a focus changed event handler (uia) on a background MTA thread for updating a list of elements for the current active window which gets fired multiple times in one second when changing active window. I am trying to make it to go once and then wait for one second before handling any other events. Problem at the minute is that the timer is started but never triggered? I guess there is a better way of doing this? A code example would be great.
public void HandleFocusChangedEvent(IUIAutomationElement sender)
{
// A focus changed event has been sent by the the active window or some descendant of it.
// Check that this event hasn't arrived around the time we're removing the event handler on shutdown.
if (!_fAddedEventHandler)
{
return;
}
// All the event handler needs to do is notify the main UI thread that the
// list of elements should be refreshed to make sure it's showing the most current list.
// We only want to do this once every second So use a timer/counter
if (focusChangedCounter == 0)
{
controllerDispatcher.BeginInvoke(_focusChangedEventHandlerDelegate);
focusChangedCounter = 1;
if (focusChangedBufferTimer == null)
{
focusChangedBufferTimer = new System.Windows.Forms.Timer();
focusChangedBufferTimer.Tick += new EventHandler(focusChangedBufferTimer_Tick);
focusChangedBufferTimer.Interval = 1000;
focusChangedBufferTimer.Start();
}
}
}
private void focusChangedBufferTimer_Tick ( object sender, EventArgs e)
{
focusChangedCounter = 0;
focusChangedBufferTimer.Stop();
focusChangedBufferTimer = null;
}
Try this: With each event trigger, reset the timer.
public partial class Form1 : Form
{
Timer t = new Timer();
public Form1()
{
InitializeComponent();
t.Interval = 1000;
t.Tick += ((ss, ee) => {
t.Enabled = false;
focusChangedCounter = 0;
focusChangedBufferTimer.Stop();
focusChangedBufferTimer = null;
});
}
private void HandleFocusChangedEvent(object sender, EventArgs e)
{
t.Enabled = false;
t.Enabled = true;
}
}

C# Timer inside a property

I'm trying to implement a timer for a checkbox. The binding for the checkbox is done using the CaptureColorBind property. When ever I click the capture color checkbox (captureColor = true), it needs to be checked for 5 seconds and then checkbox needs to be unchecked. I'm trying to print the datetime before and after the timer to verify. Its printing the before time properly, but the datetime I print in the elapsed event handler gets printed n times depending on the number of times I click the capture color checkbox. That is the first time I click, it prints the date and time once, the second time I click, it prints twice and so on. Not sure what I'm doing wrong.
private System.Timers.Timer timer = new System.Timers.Timer();
public bool CaptureColorBind
{
get
{
return this.captureColor;
}
set
{
this.captureColor = value;
if (captureColor == true)
{
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine();
timer.Elapsed += new ElapsedEventHandler(capturecolor_timer);
timer.Interval = 5000;
timer.Enabled = true;
}
if (null != this.PropertyChanged)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("CaptureColorBind"));
}
}
}
// Timer for capturecolor checkbox
private void capturecolor_timer(object sender, ElapsedEventArgs e)
{
timer.Enabled = false;
this.captureColor = false;
//this.colorCheckbox.IsChecked = false;
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine();
if (null != this.PropertyChanged)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("CaptureColorBind"));
}
}
You are adding a new event handler every time the value is set. You should only add it once.
Try adding the event handler in the object's constructor so it only gets set once, and just re-enabling the timer when the property is set.
private System.Timers.Timer timer = new System.Timers.Timer();
public MyObject()
{
timer.Elapsed += new ElapsedEventHandler(capturecolor_timer);
timer.Interval = 5000;
}

How to pause timer in windows phone?

In this code after starting timer again it starts from the current value instead of the vale it stopped. How to pause this timer?
public Page1()
{
InitializeComponent();
_rnd = new Random();
_timer = new DispatcherTimer();
_timer.Tick += new EventHandler(TimerTick);
_timer.Interval = new TimeSpan(0, 0, 0, 1);
}
void TimerTick(object sender, EventArgs e)
{
var time = DateTime.Now - _startTime;
txtTime.Text = string.Format(Const.TimeFormat, time.Hours, time.Minutes, time.Seconds);
}
public void NewGame()
{
_moves = 0;
txtMoves.Text = "0";
txtTime.Text = Const.DefaultTimeValue;
Scrambles();
while (!CheckIfSolvable())
{
Scrambles();
}
_startTime = DateTime.Now;
_timer.Start();
//GridScrambling.Visibility = System.Windows.Visibility.Collapsed;
}
private void Pause_Click(object sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
NavigationService.Navigate(new Uri("/Page4.xaml", UriKind.Relative));
_timer.Stop();
}
private void Play_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
_timer.Start();
}
As this says that the Stop method only changes the IsEnabled property and this says that this property only prevents the Tick event to be raised, I don't think that there is a method to simply 'pause' the timer. The best way is to reinitialize the timer each time you have "paused" it, if you really want it to start clean again.
But I do not think that this is you real problem. When you pause your game the timer stops working. When you continue it the timer starts working again. When you now try the calculate the time from THIS moment till the start time, then you make a big mistake: you have to ignore the paused time. Because when you play the game 2s, then pause it for 10s and then continue the game, the timer shows 12s, instead of 2s, doesn't it? Maybe you should store the paused times in a variable and substract that from the real game time.

C# timer I can speed up but not slow down

I have a timer event setup and I would like to change how often the timer event happens by reading a number from a text box. If the box is '10' and you click the update button the event would trigger every 10ms then if you changed to '100' and clicked it would happen every 100ms and so on.
When I run the program however, i can speed up the event frequency (e.g. 100ms to 10ms) but I cannot slow it down (e.g. 10ms to 100ms). Here is the piece of my code that changes the timer when I click:
private void TimerButton_Click(object sender, EventArgs e)
{
getTime = ImgTimeInterval.Text;
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = false;
timer.Interval = timerMS;
timer.Elapsed += new ElapsedEventHandler(timerEvent);
timer.AutoReset = true;
timer.Enabled = true;
}
}
public void timerEvent(object source, System.Timers.ElapsedEventArgs e)
{
label1.Text = counter.ToString();
counter = (counter + 1) % 100;
}
If anyone knows what I may be doing wrong it would be greatly appreciated.
The problem with this code is, that you create a new Timer each time you click the button. Try to create the timer outside the method. You think it's only goes faster, but instead multiple timers trigger the timerEvent
private System.Timers.Timer _timer;
private void CreateTimer()
{
_timer = new System.Timers.Timer();
_timer.Enabled = false;
_timer.Interval = 100; // default
_timer.Elapsed += new ElapsedEventHandler(timerEvent);
_timer.AutoReset = true;
_timer.Enabled = true;
}
private void TimerButton_Click(object sender, EventArgs e)
{
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
_timer.Interval = timerMS;
}
}
public void timerEvent(object source, System.Timers.ElapsedEventArgs e)
{
label1.Text = counter.ToString();
counter = (counter + 1) % 100;
}
Make sure that the CreateTimer is called in the constructor/formload. Also you can now stop the timer within another button event. With _timer.Enabled = false;
You're always creating a new timer and never stopping the old timer. When you "change" it from 100 to 10 your 100ms timer is still firing every 100 ms, so every 100ms two timers are firing at around the same time.
You need to "remember" the old timer so that you can stop it. Or, better yet, just have only one timer that you change the interval on.
private System.Timers.Timer timer = new System.Timers.Timer();
public Form1()
{
timer.Enabled = false;
timer.AutoReset = true;
timer.Elapsed += timerEvent;
}
private void TimerButton_Click(object sender, EventArgs e)
{
getTime = ImgTimeInterval.Text;
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
timer.Interval = timerMS;
timer.Enabled = true;
}
}
Well the basic problem is that you're building a new one every time. Make a private timer:
private System.Timers.Timer _timer = new System.Timers.Timer();
and then fix it up when the button is clicked:
if (isNumeric)
{
_timer.Stop();
_timer.Interval = timerMS;
_timer.Start();
}
and then in the .ctor, do this:
_timer.Elapsed += new ElapsedEventHandler(timerEvent);
Now you have a single timer that you are just modifying as the user changes the value in the text box.

Categories

Resources