Winform 空闲时间(鼠标键盘无操作)

前言

Winform 在特定情况下,需要判断软件空闲时间(鼠标键盘无操作),然后在做一下一些操作。

实现

做了一个简单的例子,新建一个窗体,然后拖两个控件(Timer控件和label控件)

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace LastInPut
{
    public partial class FrmLastInfo : Form
    {
        [StructLayout(LayoutKind.Sequential)]
        struct LASTINPUTINFO
        {
            [MarshalAs(UnmanagedType.U4)]
            public int Size;
            [MarshalAs(UnmanagedType.U4)]
            public uint Time;
        }
        [DllImport("user32.dll")]
        static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
        static long GetLastInputTime()
        {
            LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
            vLastInputInfo.Size = Marshal.SizeOf(vLastInputInfo);
            if (!GetLastInputInfo(ref vLastInputInfo)) return 0;
            return Environment.TickCount - (long)vLastInputInfo.Time;
        }

        public FrmLastInfo()
        {
            InitializeComponent();
        }
        //{GetLastInputTime()/1000}为系统空闲时间,
        private void tmrLastInfo_Tick(object sender, EventArgs e)
        {
            label1.Text = $"空闲时间{GetLastInputTime()/1000}秒";
        }
    }
}

效果图

posted @ 2021-01-19 17:20  故人与猫  阅读(368)  评论(0编辑  收藏  举报