Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Retrieving the Operating System Idle Time, Uptime and Last Input Time

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.

On Monday, June 4th 2007 at 08:59 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.6 with 22 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project (Visual Studio 2005)

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.

Idle Timer Form

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.

Idle Timer
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Yaniv on Wednesday, June 6th 2007 at 03:10 PM

Is there a way to get the idle time of a computer over the network?

by Andrei Pociu on Wednesday, June 6th 2007 at 04:11 PM

Not unless you write an application using this code and run it as a service on the network computer.

by yaniv on Thursday, June 7th 2007 at 02:26 PM

WIll you be kind to give me some advice how to write that service?
or how to run it as service?

by bahram on Monday, June 11th 2007 at 12:10 PM

by Kenji on Tuesday, June 12th 2007 at 08:48 PM

I am trying to learn how to do this for a long time and you certainly help me alot. I think my project can get extra marks now. =D

by Grant on Wednesday, June 11th 2008 at 10:31 AM

I keep getting a System.Security.Permissions.SecurityPermission error message. Anyone have any ideas why this may be?

by Jagat on Thursday, June 12th 2008 at 02:33 AM

this code is really marvelleous....

thanks dude.

by Venkat on Friday, July 4th 2008 at 07:19 AM

This is really a good work. Idle time is calculated based on Last Input.If any backgroud process like file copy or download runs,how we can track that also? - Thanks in advance.

by fvgsdgv on Wednesday, December 10th 2008 at 08:09 AM

gfdgsd

by Jaydel on Thursday, January 1st 2009 at 11:17 AM

This is really good code but I noticed that if a computer is up for 25 days or more the numbers are not correct.

Environment.TickCount -1791175703 int

After 25 days the tickcount goes to the smallest number and then starts going back to 0

by souvik on Friday, January 23rd 2009 at 04:15 AM

The concept is very fine but I work on Dreamwever
with IIs support How can I run this code?
bcoz provided code is not running in my environment

by souvik on Friday, January 23rd 2009 at 04:15 AM

The concept is very fine but I work on Dreamwever
with IIs support How can I run this code?
bcoz provided code is not running in my environment

by souvik on Friday, January 23rd 2009 at 04:15 AM

The concept is very fine but I work on Dreamwever
with IIs support How can I run this code?
bcoz provided code is not running in my environment

by souvik on Friday, January 23rd 2009 at 04:16 AM

The concept is very fine but I work on Dreamwever
with IIs support How can I run this code?
bcoz provided code is not running in my environment

by souvik on Friday, January 23rd 2009 at 04:16 AM

The concept is very fine but I work on Dreamwever
with IIs support How can I run this code?
bcoz provided code is not running in my environment

by Bad programmer on Sunday, April 19th 2009 at 06:37 AM

Very good one.. thanks

by none on Tuesday, October 27th 2009 at 12:20 PM

lol'ed at souvik

lol

by Martin on Saturday, October 31st 2009 at 01:24 AM

IT is good,
Do you have it on VB.Net?

Thanks a million.

by Suresh on Saturday, October 31st 2009 at 05:49 AM

Imports System.Runtime.InteropServices

<DllImport("User32.dll")> _
Private Shared Function GetLastInputInfo(ByRef lii As LASTINPUTINFO) As Boolean
End Function

' Unmanaged function from user32.dll
' Struct we'll need to pass to the function
Friend Structure LASTINPUTINFO

Public cbSize As System.UInt32

Public dwTime As System.UInt32

End Structure


Public Shared Function GetIdle() As UInteger
Dim lii As New LASTINPUTINFO()
lii.cbSize = Convert.ToUInt32((Marshal.SizeOf(lii)))
GetLastInputInfo(lii)
Return Convert.ToUInt32(Environment.TickCount) - lii.dwTime
End Function

by Rich on Friday, January 15th 2010 at 12:09 PM

I think I'm gonna put some logic in to display the uptime in minutes or hours or days. If you haven't rebooted in a couple weeks, the number of seconds isn't real meaningful.

by Rich on Friday, January 15th 2010 at 12:43 PM

Instead of using this statement:
lblSystemUptime.Text = Convert.ToString(systemUptime / 1000) " seconds";


If you use the following it is more meaningful if your uptime is more than a minute:

string strUptimeResult = string.Empty;

strUptimeResult = Convert.ToString(Environment.TickCount / 86400000) " days, ";

strUptimeResult = Convert.ToString(Environment.TickCount / 3600000 % 24) " hours, ";

strUptimeResult = Convert.ToString(Environment.TickCount / 60000 % 60) " minutes, ";

strUptimeResult = Convert.ToString(Environment.TickCount / 1000 % 60) " seconds.";

lblSystemUptime.Text = strUptimeResult;

by Rich on Friday, January 15th 2010 at 12:45 PM

EDIT TO MY PREVIOUS POST: It has to be like this instead:

strUptimeResult = Convert.ToString(Environment.TickCount / 86400000) " days, ";

strUptimeResult = Convert.ToString(Environment.TickCount / 3600000 % 24) " hours, ";

strUptimeResult = Convert.ToString(Environment.TickCount / 60000 % 60) " minutes, ";

strUptimeResult = Convert.ToString(Environment.TickCount / 1000 % 60) " seconds.";

lblSystemUptime.Text = strUptimeResult;

I don't know where the 's went before.

by Rich on Friday, January 15th 2010 at 12:46 PM

Last time... the plus sign is not displaying on this page for some reason. but each of those strUpTimeResult statemnts should be plus= for concatenation instead of just equal.

by Prema on Monday, March 8th 2010 at 06:41 AM

Thanks a lot..........

by Sachet on Thursday, July 1st 2010 at 06:22 AM

As a part of the application which m making..i want to calculate the total data transfer between particular interval of time..ie the total amont of download n uploaded data..by the user..cn any1 provide me with d code to calculate the total data transfer in asp.net for web application


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia

Other Resources