Reputation: 479
I have a C# WinForms application that has a panel
. The panel loads a UserControl
and the UserControl
contains a DataGridView
.
In my UserControl
, I have an event handler for the MouseDown
event on the DataGrid
private void palletsGrid_MouseDown(object sender, MouseEventArgs e)
{
try
{
EventHandler handler = onScrolling;
if (handler != null)
{
handler(this, new EventArgs());
}
}
Catch (Exception ex)
{
Logging.LogWarn("Mouse down error: ", ex);
}
}
Where onScrolling
is a publicly declared EventHandler
property.
I deal with this EventHandler
in the main form because, I have a timer that auto refreshes every 5 seconds. So I need the main form to know to stop refreshing when this event (scrolling through the DataGridView
) happens.
In my main form, this is what I am doing:
private void userControl_ScrollEvent(object sender, EventArgs e)
{
try
{
timer1.Stop();
Timer pauseTimer = new Timer();
pauseTimer.Interval = 60000;
pauseTimer.Start();
pauseTimer.Tick += new System.EventHandler(pauseTimer_Tick);
}
catch (Exception ex)
{
Logging.LogFatal("Scroll event capture error: ", ex);
}
}
What this does is, when the user is scrolling through the DataGridView
, the main form stops the auto refresh for 60 seconds. Once the 60 second pauseTimer
ticks, the refreshTimer
resumes like normal.
Problem:
I need my form to know when I touch the screen twice. As in, if I touch the screen now, the timer starts. Does not refresh for 60 seconds. If I touch it again, the 60 seconds needs to start from the second touch. Not the first. So every time I touch the screen, the pauseTimer
needs to restart.
Upvotes: 0
Views: 2841
Reputation: 818
Like @FrankM points out, you should not create a new timer everytime you scroll. You should always be careful when creating timers (System.Windows.Forms.Timer) in code, if you do, you have to make sure they are disposed properly. The easiest way is to add timers from the designer, this way proper cleanup is taken care of for you. More on disposal of System.Windows.Forms.Timers
Solution 1: Add a pausetimer in the designer and restart it in the scroll event. How to restart a timer may not be obvious, but you do it by first disabling the timer, then enable it:
try
{
timer1.Enabled = false;
//Set interval and tick-handler from designer
pauseTimer.Enabled = false;
pauseTimer.Enabled = true;
}
catch (Exception ex)
{
Logging.LogFatal("Scroll event capture error: ", ex);
}
Solution 2: Get rid of the pause timer and just change the interval of your refresh-timer.
try
{
//Assume that this is the refreshtimer. In the Tick-eventhandler
//you reset interval to default refresh intervals
timer1.Interval = 60000;
timer1.Enabled = false;
timer1.Enabled = true;
}
catch (Exception ex)
{
Logging.LogFatal("Scroll event capture error: ", ex);
}
Upvotes: 2