본문 바로가기
.NET

C# Idle 상태 체크

by leo21c 2021. 7. 31.
SMALL

 

using System;
using System.Runtime.InteropServices;

namespace BlahBlah
{
    public static class IdleTimeDetector
    {
        [DllImport("user32.dll")]
        static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

        public static IdleTimeInfo GetIdleTimeInfo()
        {
            int systemUptime = Environment.TickCount,
                lastInputTicks = 0,
                idleTicks = 0;

            LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
            lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
            lastInputInfo.dwTime = 0;

            if (GetLastInputInfo(ref lastInputInfo))
            {
                lastInputTicks = (int)lastInputInfo.dwTime;

                idleTicks = systemUptime - lastInputTicks;
            }

            return new IdleTimeInfo
            {
                LastInputTime = DateTime.Now.AddMilliseconds(-1 * idleTicks),
                IdleTime = new TimeSpan(0, 0, 0, 0, idleTicks),
                SystemUptimeMilliseconds = systemUptime,
            };
        }
    }

    public class IdleTimeInfo
    {
        public DateTime LastInputTime { get; internal set; }

        public TimeSpan IdleTime { get; internal set; }

        public int SystemUptimeMilliseconds { get; internal set; }
    }

    internal struct LASTINPUTINFO
    {
        public uint cbSize;
        public uint dwTime;
    }
}

사용할 때 아래와 같이 이용

var idleTime = IdleTimeDetector.GetIdleTimeInfo();

if (idleTime.IdleTime.TotalMinutes >= 5)
{
    // They are idle!
}

참고한 싸이트

https://stackoverflow.com/questions/4963135/wpf-inactivity-and-activity/4970019#4970019

 

WPF inactivity and activity

I'm trying to handle user inactivity and activity in a WPF application to fade some stuff in and out. After a lot of research, I decided to go with the (at least in my opinion) very elegant solutio...

stackoverflow.com

테스트 한 결과 정상적으로 잘 작동한다.

이것을 이용하면 idle 상태를 체크해서 자동 로그아웃 등을 사용할 수 있을 것으로 판단된다.

https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getlastinputinfo

 

GetLastInputInfo function (winuser.h) - Win32 apps

Retrieves the time of the last input event.

docs.microsoft.com

Retrieves the time of the last input event.

 

LIST