I'm attempting to add a countdown to a data grid view which goes from 2 minutes to 0. When the button is pressed it should add a new row with a token and a 2 minute countdown. When the 2 minute countdown reaches 0 that row should be deleted. I have the token already set up and at the moment instead of a countdown I'm using time in 2 minutes. The main thing I want to achieve is deleting the token after 2 minutes which is when the token expires.
Here's my current code:
//Add Token To Grid
int row = 0;
TokenGrid.Rows.Add();
row = TokenGrid.Rows.Count - 2;
TokenGrid["CaptchaToken", row].Value = CaptchaWeb.Document.GetElementById("gcaptcha").GetAttribute("value");
//Time Left
TokenGrid["ExpiryTime", row].Value = DateTime.Now.AddMinutes(2).ToLongTimeString();
In timer's timeelapsed()
event, compare the value ExpiryTime
of each row with current time. If ExpiryTime < current time
, delete the row.
Implement a timer (see How do I create a timer in WPF? ):
const int MAX_DURATION = 120;
System.Windows.Threading.DispatcherTimer dispatcherTimer;
// In the OnClick
DateTime timerStart = DateTime.Now;
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
EventHandler handler = new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Tick += handler;
dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// Display seconds
var currentValue = DateTime.Now - timerStart;
TokenGrid["ExpiryTime", row].Value = currentValue.Seconds.ToString();
// When the MAX_DURATION (2 minutes) is reached, stop the timer
if (currentValue >= MAX_DURATION) {
dispatcherTimer.Tick -= handler;
dispatcherTimer.Stop();
TokenGrid.Rows.RemoveAt(row);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.