Landon Hammond
Landon Hammond

Reputation: 138

How to stop Timer Tick from spamming?

I am trying to implement the Idle detection from this thread: Hide mouse cursor after an idle time

I have made very little change to it, but I am having a problem with it spamming the test MessageBox.

void activityWorker_Tick(object sender, EventArgs e)
    {
        bool checkIdle = (User32Interop.GetLastInput() > activityThreshold);

        if (isIdle != checkIdle)
        {
            if (checkIdle && (DateTime.Now.Subtract(idleCheckTimestamp) > TimeSpan.FromMinutes(1)))
            {
                System.Windows.Forms.MessageBox.Show("Idle: " + count);
                idleCheckTimestamp = DateTime.Now;
                count++;
            }

            isIdle = checkIdle;
        }
    }

Each time this event fires,the messagebox is displayed, but nothing after it runs, making it seem impossible to stop it from spamming. It does not reset the timestamp, nor does it increment the count variable, it just spams a messagebox with "Idle: 0".

Can anyone point me in the correct direction on what to do to make it stop spamming? I want the system to be constantly checking for idle time, but I only want my code to fire once every min. or so if it is infact idle.

Upvotes: 0

Views: 218

Answers (2)

Lior
Lior

Reputation: 171

as Hans wrote you can disable the timer (Enabled=false) right before System.Windows.Forms.MessageBox.Show("Idle: " + count); and enabling it again right after

Upvotes: 1

Ashish Charan
Ashish Charan

Reputation: 2387

You can do that by keeping a variable and storing when last you sent a message, and then you can check whether 1 minute has passed and then again you can show message. For Example:

DateTime LastMessageSentOn;
//Initialize it in constructor or anywhere else before using.

void activityWorker_Tick(object sender, EventArgs e)
{
    bool checkIdle = (User32Interop.GetLastInput() > activityThreshold);

    if (isIdle != checkIdle)
    {
        if (checkIdle && LastMessageSentOn.AddMintues(1)<DateTime.Now)
        {
            System.Windows.Forms.MessageBox.Show("Idle: " + count);
            LastMessageSentOn = DateTime.Now;
            count++;
        }

        isIdle = checkIdle;
    }
}

Upvotes: 1

Related Questions