Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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 ?

like image 776
MD TAHMID HOSSAIN Avatar asked Dec 23 '13 09:12

MD TAHMID HOSSAIN


People also ask

How is idle time calculated C#?

You can use user32. dll and LASTINPUTINFO[^] to calculate the system ideal time.

What is meant by idle time in computer?

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.


1 Answers

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);
like image 154
Adriano Repetti Avatar answered Sep 30 '22 11:09

Adriano Repetti