Hi tpathan,
Use the System.Runtime.InteropServices LASTINPUTINFO class to get the IdleTime and LastInputTime.
Refer below code.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Idle_Timeout_Windows_CS
{
internal struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
public partial class Form1 : Form
{
public static bool IsOpen { get; set; }
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
// Check idel time after 10 secs.
if (GetIdleTime() > 10000 && !IsOpen)
{
MessageBox.Show("Your Session is expired.");
IsOpen = true;
}
}
[DllImport("User32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO lastInputInfo);
[DllImport("Kernel32.dll")]
private static extern uint GetLastError();
public static uint GetIdleTime()
{
LASTINPUTINFO lastUserAction = new LASTINPUTINFO();
lastUserAction.cbSize = (uint)Marshal.SizeOf(lastUserAction);
GetLastInputInfo(ref lastUserAction);
return ((uint)Environment.TickCount - lastUserAction.dwTime);
}
public static long GetLastInputTime()
{
LASTINPUTINFO lastUserAction = new LASTINPUTINFO();
lastUserAction.cbSize = (uint)Marshal.SizeOf(lastUserAction);
if (!GetLastInputInfo(ref lastUserAction))
{
throw new Exception(GetLastError().ToString());
}
return lastUserAction.dwTime;
}
}
}