Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetLastInputTime shows impossible time?

Tags:

c#

winapi

To determine, if PC was not used for certain amount of time, I'm using Win32API.GetLastInputTime() method. I'm just subtracting its value from DateTime.Now, and compare it with some value, stored in settings.

It worked perfectly before, but recently GetLastInputTime started to show completely ridiculous results - it shows me future time. Today it shows me July 2nd of 2016.

So, does anyone has any idea, what's happening? How does GetLastInputTime get time, and how it is possible, that this time is future one?

like image 476
lentinant Avatar asked May 18 '26 00:05

lentinant


2 Answers

Since GetLastInputTime returns ticks as UInt32 (DWORD)

https://msdn.microsoft.com/en-us/library/windows/desktop/ms724408(v=vs.85).aspx

you can have an integer overflow:

The elapsed time is stored as a DWORD value. Therefore, the time will wrap around to zero if the system is run continuously for 49.7 days. To avoid this problem, use the GetTickCount64 function. Otherwise, check for an overflow condition when comparing times.

And thus have future dates:

   13 May 2016 + 49.7 days == 2 July 2016
like image 164
Dmitry Bychenko Avatar answered May 20 '26 16:05

Dmitry Bychenko


I think you can not use DateTime.Now because it depends on the time zone.

As described here, you have to use Environment.TickCount to get the idle time.

like image 24
JanDotNet Avatar answered May 20 '26 15:05

JanDotNet