Question

I've developed a windows form program (an E-POS with user login), but it as a requirement I want it to log the user out of the system after 30 minutes. I found the following code and played around with it, but I get the error:

a field initializer cannot reference the non-static field, method or property...

by the first instance of _TimerTick appearing in the code.

private System.Threading.Timer timer = new System.Threading.Timer(
    _TimerTick,
    null,
    1000 * 30 * 60,
    Timeout.Infinite);

private void _OnUserActivity(object sender, EventArgs e)
{
    if (timer != null)
    {
        timer.Change(1000 * 30 * 60, Timeout.Infinite);
    }
}

private void _TimerTick(object state)
{
    var myLogin = new LoginForm(this);
    myLogin.userCode = null;
    MainControlsPanel.Hide(); 

    // the user has been inactive for 30 minutes; log him out
}
Was it helpful?

Solution

My opinion would be to assign your timer in your class constructor:

instead of

private System.Threading.Timer timer = new System.Threading.Timer(
_TimerTick,
null,
1000 * 30 * 60,
Timeout.Infinite);

I would use something like that:

    class YourClass
{
private System.Threading.Timer timer;
public YourClass()
{
    timer = new System.Threading.Timer(
    _TimerTick,
    null,
    1000 * 30 * 60,
    Timeout.Infinite);
}
//...
}

Or there is another way to walkthrough

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top