0

I am writing a c# Winform application and I need to close session if the computer is idle for 5 seconds. The application is like a restaurant application, when the waiter leaves his session open, I will close it after 5 seconds.

I found some code but I dont know how to use it and how to trigger it

using System.Runtime.InteropServices;

[DllImport("User32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);   

internal struct LASTINPUTINFO
{
    public uint cbSize;

    public uint dwTime;
}

Can anybody help me with this?

Arif YILMAZ
  • 5,754
  • 26
  • 104
  • 189

1 Answers1

7

Follow these steps:

1- Add a Timer to your Form.

2- Set its interval property to 1000 (set it in form_load or in design mode from Properties window).

3-Add this method to your Form class.

public static uint GetIdleTime()
{
     LASTINPUTINFO LastUserAction = new LASTINPUTINFO();
     LastUserAction.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(LastUserAction);
     GetLastInputInfo(ref LastUserAction);
     return ((uint)Environment.TickCount - LastUserAction.dwTime);
}

4- in Form_Load start the timer:

timer1.Start();

5- in timer tick event check GetIdleTime(), for example if it is greater than 5000 means application was idled since 5 seconds ago.

private void timer1_Tick(object sender, EventArgs e)
{
    if (GetIdleTime() > 5000)  
       Application.Exit();//For Example
}
Aria
  • 3,724
  • 1
  • 20
  • 51