WinForm程序 一段時間不運行自動退出

-----------------------------------------------------------------------------

應用場景:實現程序一段時間不運行自動關閉的方法

============================================

功能實現代碼如下所示:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Text;
 7 using System.Windows.Forms;
 8 using System.Net;
 9 using System.IO;
10 using System.Security.Cryptography.X509Certificates;
11 using System.Net.Security;
12 
13 namespace DemoDataGridView
14 {
15  public partial class Form1 : Form, IMessageFilter
16  {
17   private int m_WaitMinute = 0;
18   System.Windows.Forms.Timer MyTimer;
19   public Form3()
20   {
21    InitializeComponent();
22    MyTimer = new Timer();
23    MyTimer.Interval = 1000;
24    MyTimer.Tick += new EventHandler(MyTimer_Tick);
25    Application.Idle += new EventHandler(Application_Idle);
26   }
27   void MyTimer_Tick(object sender, EventArgs e)
28   {
29    if (m_WaitMinute < 60)
30    {
31     MyTimer.Enabled = true;
32     MyTimer.Interval = 10000; //10秒
33     m_WaitMinute += 1;
34     // this.Opacity = 1.0 - Convert.ToDouble(m_WaitMinute / 60.0);
35    }
36    else
37    {
38     MyTimer.Enabled = false;
39    }
40   }
41   void Application_Idle(object sender, EventArgs e)
42   {
43    if (m_WaitMinute == 0)
44    {
45     System.IO.File.WriteAllText("D:\\1.txt", DateTime.Now.ToString());
46     MyTimer.Start();
47    }
48    else
49    {
50     if (m_WaitMinute >= 6)
51     {
52      System.IO.File.WriteAllText("D:\\2.txt", DateTime.Now.ToString());
53      this.Close();
54     }
55    }
56   }
57   public bool PreFilterMessage(ref Message m)
58   {
59    if (m_WaitMinute != 0)
60    {
61     m_WaitMinute = 0;
62     MyTimer.Enabled = false;
63     return true;
64    }
65    return false;
66   }
67  }
68 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章