简体   繁体   中英

How to find how long my computer is being idle (idle time) on C# desktop

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 ?

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM