Controls Needed :
BackgroundWorker
Explanation :
This is to help you to calculate user idle time using windows application.
When user idle for some it will start calculating their idle time , when user
again user their system it will end idle time.
Code :
#region "Idle
Time"
// This is to specify minutes to calculate idle time. Suppose if you want
to calculate for above 10 minutes of user idle time .
private int iTimePeriod = 10;
bool
bCalculateIdleTime = false;
DateTime dtIdleStartTime = DateTime.Now;
// 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;
}
#endregion "Idle Time"
private void bgWorkerIdleUser_DoWork(object
sender, DoWorkEventArgs e)
{
try
{
while
(true)
{
//
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;
}
TimeSpan
t = TimeSpan.FromSeconds(IdleTicks / 1000);
if
(t.Hours == 0 && t.Minutes == 0 && t.Seconds == 0)
{
int
iTotalSeconds = (int)Math.Round((DateTime.Now - dtIdleStartTime).TotalSeconds);
if (iTotalSeconds >= (iTimePeriod * 60) &&
iTotalSeconds > 0)
{
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName()).Where(address =>
address.AddressFamily == AddressFamily.InterNetwork).First();
}
bCalculateIdleTime = false;
}
else
if (t.Seconds > 0)
{
if (!bCalculateIdleTime)
{
bCalculateIdleTime
= true;
dtIdleStartTime = DateTime.Now;
}
}
System.Threading.Thread.Sleep(100);
}
}
catch
(Exception ex)
{
ExceptionHandler.HandleException(ex.ToString());
}
}
No comments:
Post a Comment