Detecting User Activity

前端 未结 2 562
悲哀的现实
悲哀的现实 2020-12-09 05:56

I need to create a program that monitors a computer for activity. Such as a mouse move, mouse click or keyboard input. I don\'t need to record what has happened just that th

2条回答
  •  眼角桃花
    2020-12-09 06:17

    Thank you LordCover. This code is from here. This class takes control of the keyboard and mouse controls for you. You can use in a timer like this:

    private void timer1_Tick(object sender, EventArgs e)
    {
        listBox1.Items.Add(Win32.GetIdleTime().ToString());
        if (Win32.GetIdleTime() > 60000) // 1 minute
        {
            textBox1.Text = "SLEEPING NOW";
        }
    }
    

    Main code for control. Paste to your form code.

    internal struct LASTINPUTINFO
    {
        public uint cbSize;
        public uint dwTime;
    }
    
    public class Win32
    {
        [DllImport("User32.dll")]
        public static extern bool LockWorkStation();
    
        [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);
        }
    
        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;
        }
    }
    

提交回复
热议问题