Development Tip

C #-OS와 마지막 사용자 상호 작용 시간 감지

yourdevel 2020. 11. 24. 19:59
반응형

C #-OS와 마지막 사용자 상호 작용 시간 감지


사용자가 유휴 상태인지 확인하기 위해 컴퓨터와 마지막으로 상호 작용 한 시간을 감지해야하는 작은 트레이 응용 프로그램을 작성 중입니다.

사용자가 마지막으로 마우스를 이동하거나 키를 누르거나 컴퓨터와 어떤 방식 으로든 상호 작용 한 시간을 검색 할 수있는 방법이 있습니까?

화면 보호기를 표시하거나 전원을 끌 때 등을 결정하기 위해 Windows가 분명히 이것을 추적한다고 생각하므로 직접 검색하는 Windows API가 있다고 가정하고 있습니까?


GetLastInputInfo . PInvoke.net에 문서화되었습니다 .


다음 네임 스페이스 포함

using System;
using System.Runtime.InteropServices;

그리고 다음을 포함

internal struct LASTINPUTINFO 
{
    public uint cbSize;

    public uint dwTime;
}

/// <summary>
/// Helps to find the idle time, (in milliseconds) spent since the last user input
/// </summary>
public class IdleTimeFinder
{
    [DllImport("User32.dll")]
    private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);        

    [DllImport("Kernel32.dll")]
    private static extern uint GetLastError();

    public static uint GetIdleTime()
    {
        LASTINPUTINFO lastInPut = new LASTINPUTINFO();
        lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut);
        GetLastInputInfo(ref lastInPut);

        return ((uint)Environment.TickCount - lastInPut.dwTime);
    }
/// <summary>
/// Get the Last input time in milliseconds
/// </summary>
/// <returns></returns>
    public static long GetLastInputTime()
    {
        LASTINPUTINFO lastInPut = new LASTINPUTINFO();
        lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut);
        if (!GetLastInputInfo(ref lastInPut))
        {
            throw new Exception(GetLastError().ToString());
        }       
        return lastInPut.dwTime;
    }
}

tickcount를 시간으로 변환하려면 다음을 사용할 수 있습니다.

TimeSpan timespent = TimeSpan.FromMilliseconds(ticks);

노트. 이 루틴은 TickCount라는 용어를 사용하지만 값은 밀리 초 단위이며 Ticks와 동일하지 않습니다.

From MSDN article on Environment.TickCount

Gets the number of milliseconds elapsed since the system started.


Code:

 using System;
 using System.Runtime.InteropServices;

 public static int IdleTime() //In seconds
    {
        LASTINPUTINFO lastinputinfo = new LASTINPUTINFO();
        lastinputinfo.cbSize = Marshal.SizeOf(lastinputinfo);
        GetLastInputInfo(ref lastinputinfo);
        return (((Environment.TickCount & int.MaxValue) - (lastinputinfo.dwTime & int.MaxValue)) & int.MaxValue) / 1000;
    }

참고URL : https://stackoverflow.com/questions/1037595/c-sharp-detect-time-of-last-user-interaction-with-the-os

반응형