WinFrom系统长时间不操作则进行关闭+关闭窗口倒计时

标题:WinFrom系统长时间不操作则进行关闭+关闭窗口倒计时

1.首先在界面添加两个timer
2.在窗体运行是开启第一个timer
3.( 0x0202://鼠标左键UP,0x0205://鼠标右键UP,0x0203://鼠标左键双击,case 0x201://鼠标左键Down,case 0x100://键盘按下)
public Form7()
{
InitializeComponent();
MyMessager msg = new MyMessager();
Application.AddMessageFilter(msg);
timer1.Start();
}

    static int iOperCount = 0;
    static IntPtr hwnd;
    static int t;
    internal class MyMessager : IMessageFilter
    {
        public bool PreFilterMessage(ref Message m)
        {
            //如果检测到有鼠标或则键盘的消息,则使计数为0.....
            if (m.Msg == 0x0202 || m.Msg == 0x0205 || m.Msg == 0x0203 || m.Msg == 0x201||
                m.Msg == 0x100)
            {
                iOperCount = 0;
            }
            return false;
        }
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        iOperCount++;
        label1.Text = iOperCount.ToString();
        if (iOperCount > 120)
        {
            t = 5;
            timer2.Enabled = true;
            timer1.Enabled = false;
            if (MessageBox.Show("系统关机提示:", "系统将于" + t + "秒后关机", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
            {
                timer2.Enabled = false;
                timer1.Enabled = true;
                iOperCount = 0;
                label1.Text = "1";
            }
            else {
                Application.Exit();
            }
        }
    }
    [DllImport("user32.dll", EntryPoint = "FindWindow")]
    private static extern IntPtr FindWindow(string IpClassName, string IpWindowName);
    [DllImport("User32.dll", CharSet = CharSet.Auto)]
    public static extern int SetWindowText(IntPtr hWnd, string text);
    [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
    private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
    [DllImport("user32.dll", EntryPoint = "SendMessage")]
    private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
    const int BM_CLICK = 0xF5;
    private void timer2_Tick(object sender, EventArgs e)
    {
        hwnd = FindWindow(null, "系统将于" + t.ToString() + "秒后关机");
        t = t - 1;
        SetWindowText(hwnd, "系统将于" + t.ToString() + "秒后关机");
        if (t == 0)
        {
            IntPtr OKHwnd = FindWindowEx(hwnd, IntPtr.Zero, null, "确定");
            SendMessage(OKHwnd, BM_CLICK, 0, 0);
            timer2.Enabled = false;
        }
    }

你可能感兴趣的:(WinFrom系统长时间不操作则进行关闭+关闭窗口倒计时)