实现自动间休[原创]

首先创建两个窗口,form1,spacerest

form1下代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace spacerest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitTimer();
        }
        /// <summary>
        /// 定义一个计数器
        /// </summary>
        public static System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();

        //private int Interval = int.Parse(System.Configuration.ConfigurationManager.AppSettings["time"]);
        /// <summary>
        ///定义一个等待的时间10秒
        /// </summary>
        private int Interval = 10000;
        /// <summary>
        /// 初始化时间
        /// </summary>
        private void InitTimer()
        {
            Form1.timer1.Interval = 100;
            Form1.timer1.Enabled = true;
            Form1.timer1.Tick += new System.EventHandler(this.timer1_Tick);
        }
        /// <summary>
        /// 时间计数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            LASTINPUTINFO plii = new LASTINPUTINFO();
            unsafe
            {
                plii.cbSize = (uint)sizeof(LASTINPUTINFO);
            }
            if (GetLastInputInfo(ref plii))
            {
                //超过10分钟自动锁定程序
                if (GetTickCount() - plii.dwTime >= Interval)
                {
                    Form1.timer1.Enabled = false;
                    spacerest space = new spacerest();
                    space.ShowDialog();
                }
            }
            else
                throw new Exception("GetLastInputInfo 函数调用失败");
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct LASTINPUTINFO
        {
            public uint cbSize;
            public uint dwTime;

        }
        [DllImport("Kernel32.dll")]
        public static extern uint GetTickCount();

        [DllImport("user32.dll")]
        public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);


        public static void CloseForm()
        {
            if (ms_MainFrame != null && ms_MainFrame.IsDisposed == false)
            {
                ms_MainFrame = null;
            }

        }
        private static Form1 ms_MainFrame = null;
        public static Form1 GetMainFrame
        {
            get
            {
                return ms_MainFrame;
            }
        }
        private void systimer_Tick(object sender, EventArgs e)
        {
            this.label1.Text = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
        }
    }
}

原文地址:https://www.cnblogs.com/winnxm/p/911055.html