How to find how long my computer is being idle (idle time) on C# Desktop Application
Idle time is the total time a computer or device has been powered on, but has not been used. If a computer or computer device is idle for a set period of time, it may go into a standby mode or power off.
is there any way to get that ?
You can use user32. dll and LASTINPUTINFO[^] to calculate the system ideal time.
A computer processor is described as idle when it is not being used by any program. Every program or task that runs on a computer system occupies a certain amount of processing time on the CPU. If the CPU has completed all tasks it is idle. Modern processors use idle time to save power.
If with idle you mean time elapsed from last user input (as GetIdleTime()
function would do) then you have to use GetlastInputInfo()
function (see MSDN):
In C# you have to P/Invoke it:
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[StructLayout(LayoutKind.Sequential)]
struct LASTINPUTINFO {
public uint cbSize;
public int dwTime;
}
It'll return number of milliseconds elapsed from system boot of last user input. First thing you need is then system boot time, you have that from Environment.TickCount
(number of milliseconds from boot) then:
DateTime bootTime = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount);
Now you can have time of last input:
LASTINPUTINFO lii = new LASTINPUTINFO();
lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
GetLastInputInfo(ref lii);
DateTime lastInputTime = bootTime.AddMilliseconds(lii.dwTime);
Elapsed time will then simply be:
TimeSpan idleTime = DateTime.UtcNow.Subtract(lastInputTime);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With