Reputation: 1720
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 ?
Upvotes: 5
Views: 4172
Reputation: 67148
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);
Upvotes: 12
Reputation: 14332
Depending on your UI framework (you did not specify), you need to catch the WM_ENTERIDLE
message and store the time in which the message is received.
How should you catch this message? These guys will tell you for to do it in winforms.
Upvotes: -1