We are going into Windows's unmanaged user32.dll library in order to retrieve the operating system uptime, last activity time, and user idle time.
In this C# programming tutorial here at Geekpedia, we’re venturing into unmanaged code again. It’s the popular user32.dll that has the GetLastInputInfo() function which interests us in this tutorial. The application will work with Windows 2000, XP, Server 2003, Server 2008 and Vista.
Start by creating a form with 3 Labels: lblIdleTime, lblSystemUptime and lblLastInput. Also add a Timer tmrIdle. Set the Interval property to 1000 (1 second) and the Enabled property to True. Every time this timer ticks, we’ll check the last input time and the system uptime. Thus setting the timer to tick every 1 second is a pretty good interval for checking this, accurate but not an overkill.
Now let’s write some code. Since we’re using an unmanaged library, first comes the additional using statement:
using System.Runtime.InteropServices;
Next comes the signature function and the definition of the struct that is passed to it:
// Unmanaged function from user32.dll
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
// Struct we'll need to pass to the function
internal struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
Now it’s time to double-click the tmrIdle Timer object so that we get to its Tick event. Here comes the main code, which is self-explanatory thanks to the comments:
private void tmrIdle_Tick(object sender, EventArgs e)
{
// Get the system uptime
int systemUptime = Environment.TickCount;
// The tick at which the last input was recorded
int LastInputTicks = 0;
// The number of ticks that passed since last input
int IdleTicks = 0;
// Set the struct
LASTINPUTINFO LastInputInfo = new LASTINPUTINFO();
LastInputInfo.cbSize = (uint)Marshal.SizeOf(LastInputInfo);
LastInputInfo.dwTime = 0;
// If we have a value from the function
if (GetLastInputInfo(ref LastInputInfo))
{
// Get the number of ticks at the point when the last activity was seen
LastInputTicks = (int)LastInputInfo.dwTime;
// Number of idle ticks = system uptime ticks - number of ticks at last input
IdleTicks = systemUptime - LastInputTicks;
}
// Set the labels; divide by 1000 to transform the milliseconds to seconds
lblSystemUptime.Text = Convert.ToString(systemUptime / 1000) + " seconds";
lblIdleTime.Text = Convert.ToString(IdleTicks / 1000) + " seconds";
lblLastInput.Text = "At second " + Convert.ToString(LastInputTicks / 1000);
}
Retrieving the operating system uptime is done through managed code (Environment.TickCount), however the last activity time is retrieved through the unmanaged GetLastInputInfo() function that we prepared earlier. From then on, calculating the last input ticks is simple math: subtract the last activity milliseconds from the system uptime and there you have it.