首页 > 解决方案 > 为什么 Environment.TickCount 和键盘的 lastinputinfo.dwTime 是一样的?

问题描述

我正在努力获得使用鼠标和键盘的空闲时间。到目前为止,我得到了鼠标空闲时间,但我无法得到键盘的空闲时间。

当我检查“Environment.TickCount”和“lastInputInfo.dwTime”时,它们总是相同的,所以键盘上的空闲时间总是0。

这是获取最后输入时间的方法:

 public DateTime GetLastInputTime()
    {
        var lastInputInfo = new LASTINPUTINFO();
        lastInputInfo.dwTime = 0;
        lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);

        GetLastInputInfo(ref lastInputInfo);

        return DateTime.Now.AddMilliseconds(-(Environment.TickCount - lastInputInfo.dwTime));
    }

这是获得空闲时间的方法:

public static uint GetIdleTime()
    {
        var lastinput = new LASTINPUTINFO();
        lastinput.cbSize = (uint)Marshal.SizeOf(lastinput);

        GetLastInputInfo(ref lastinput);
        return ((uint)Environment.TickCount - lastinput.dwTime);
    }

这是键盘事件:

private void keyboard_KeyBoardKeyPressed(object sender, EventArgs e)
    {
        if (GetIdleTime() > 10000)
        {
            timer1.Enabled = false;
            MessageBox.Show("keyboard mvoe test");
            timer1.Enabled = true;
        }
        label_keyboard.Text = FormatDateTime(lastInput.GetLastInputTime());
    }

我设置了 10 秒来检查我是否在 10 秒内没有按键盘,消息会弹出。

标签: c#winformswinapi

解决方案


推荐阅读