Reputation: 1518
Is there anything that provides system idleness ? We want to use C# to get the idle time for the system across all sessions and put the machine to logout if nobody is using the machine for X minutes.
any idea about this .....
Upvotes: 0
Views: 1506
Reputation: 127563
If you are running a terminal server this can be done through group polices or through terminal services configuration
To log off a desktop session you will need to have a program that runs in the background (this will not work as a system service, it must be running as part of the interactive session) that will check the login time with GetLastInputInfo
, it then can call ExitWindowsEx
to log off.
class Program
{
[StructLayout(LayoutKind.Sequential)]
struct LASTINPUTINFO
{
public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));
[MarshalAs(UnmanagedType.U4)]
public int cbSize;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwTime;
}
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ExitWindowsEx(uint uFlags, uint dwReason);
static void Main(string[] args)
{
bool running = true;
while (running)
{
if (GetLastInputTime() > 60 * 15) //15 min idle time
{
ExitWindowsEx(0, 0);
running = false;
}
Thread.Sleep(1000 * 60); //check once per min.
}
}
static int GetLastInputTime()
{
int idleTime = 0;
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo);
lastInputInfo.dwTime = 0;
int envTicks = Environment.TickCount;
if (GetLastInputInfo(ref lastInputInfo))
{
int lastInputTick = (int)lastInputInfo.dwTime;
idleTime = envTicks - lastInputTick;
}
return ((idleTime > 0) ? (idleTime / 1000) : 0);
}
}
I needed to do this once and had trouble finding sources and this may help someone else who is goggleing this kind of question. So even though I am answering, I am down voting the question.
UPDATE: Here is a technique to get this to run as a service
Upvotes: 4