最近工作中经常遇到一个程序异常报错,如下

 

每次出现这个问题就需要点击一下“不发送”,为了及时发现程序出现这样的异常并作出响应,制作了一个小程序。

其主要作用就是每隔一段时间就检查系统中是否存在指定标题的窗口(如:InfoTV.exe),如果有就执行指定的动作(如:不发送(&D))。

程序如下:

“程序窗口名称”项只能是某窗口标题栏中的文字,如本程序的窗口名称:终结异常程序。

“执行操作名称”项只能是按钮上的文字,如:最小化、退出。

程序使用C#使用,基于.net 2.0

下载地址:https://files.cnblogs.com/happycode_k/%E7%BB%88%E7%BB%93%E5%BC%82%E5%B8%B8%E7%A8%8B%E5%BA%8F.rar

Config

View Code
 1 using System;
 2 using System.IO;
 3 using System.Drawing.Imaging;
 4 using System.Drawing;
 5 using System.Windows.Forms;
 6 
 7 namespace EEP
 8 {
 9     /// <summary>
10     /// Description of Config.
11     /// </summary>
12     public class Config
13     {
14         public Config()
15         {
16         }
17         
18         private  static int sleeptime=1000*10;
19         
20         public static int SleepTime
21         {
22             set{
23                 sleeptime=value*1000;
24             }
25             get{
26                 return sleeptime;
27             }
28         }
29         
30         public static string ApplicationPath
31         {
32             get{
33                 return Directory.GetParent(Application.ExecutablePath)+"\\";
34             }
35         }
36         
37         public static string ConfigFile
38         {
39             get{
40                 return ApplicationPath+"EEPConfig.ini";
41             }
42         }
43         
44         public static string LogFile
45         {
46             get{
47                 return ApplicationPath+"EEPLog.log";
48             }
49         }
50         
51         public static string ScreenshotDirectory
52         {
53             get{
54                 if(!Directory.Exists(ApplicationPath+"Screenshot"))
55                 {
56                     Directory.CreateDirectory(ApplicationPath+"Screenshot\\");
57                 }
58                 return ApplicationPath+"Screenshot\\";
59             }
60         }
61         
62         public static void GetDeskTop()
63         {
64             try{
65                 Image desktop= new Bitmap(Screen.PrimaryScreen.Bounds.Size.Width, Screen.PrimaryScreen.Bounds.Size.Height);
66                 Graphics g= Graphics.FromImage(desktop);
67                 g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
68                 string filename = ScreenshotDirectory+DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss") + "." + ImageFormat.Jpeg.ToString();
69                 desktop.Save(filename, ImageFormat.Jpeg);
70                 desktop=null;
71                 g=null;
72                 GC.Collect();
73             }
74             catch{}
75         }
76     }
77 }

 

MainForm

View Code
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Drawing;
  4 using System.Windows.Forms;
  5 using System.IO;
  6 using System.Text;
  7 using System.Threading;
  8 using System.Runtime.InteropServices;
  9 
 10 namespace EEP
 11 {
 12     /// <summary>
 13     /// Description of MainForm.
 14     /// </summary>
 15     public partial class MainForm : Form
 16     {
 17         [DllImport("user32.dll")]
 18         public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
 19 
 20         [DllImport("user32.dll")]
 21         public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
 22 
 23         [DllImport("user32.dll", CharSet = CharSet.Unicode)]
 24         public static extern IntPtr PostMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
 25 
 26         [DllImport("User32.dll", CharSet = CharSet.Auto)]
 27         public static extern bool SetWindowText(IntPtr hwnd, string lpString);
 28 
 29         [DllImport("User32.dll", EntryPoint = "SendMessage")]
 30         private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
 31         
 32         private Thread monitorthread;
 33         private bool ismonitor;
 34         
 35         [STAThread]
 36         public static void Main(string[] args)
 37         {
 38             Application.EnableVisualStyles();
 39             Application.SetCompatibleTextRenderingDefault(false);
 40             Application.Run(new MainForm());
 41         }
 42         
 43         public MainForm()
 44         {
 45             InitializeComponent();
 46             this.LoadConfig();
 47         }
 48         
 49         void MainFormLoad(object sender, EventArgs e)
 50         {
 51             this.HideForm();
 52             this.Start();
 53         }
 54         
 55         void Btn_exitClick(object sender, EventArgs e)
 56         {
 57             this.Exit();
 58         }
 59         
 60         void Btn_startClick(object sender, EventArgs e)
 61         {
 62             this.Start();
 63         }
 64         
 65         void Btn_stopClick(object sender, EventArgs e)
 66         {
 67             this.Stop();
 68         }
 69         
 70         private void Start()
 71         {
 72             monitorthread=new Thread(new ThreadStart(monitorthreadmethod));
 73             monitorthread.Start();
 74             btn_start.Enabled=false;
 75             btn_stop.Enabled=true;
 76         }
 77         
 78         private void Stop()
 79         {
 80             ismonitor=false;
 81             monitorthread.Abort();
 82             btn_start.Enabled=true;
 83             btn_stop.Enabled=false;
 84         }
 85         
 86         private void monitorthreadmethod()
 87         {
 88             ismonitor=true;
 89             while(ismonitor)
 90             {
 91                 for(int row=0;row<dgv_programlist.Rows.Count;row++)
 92                 {
 93                     try{
 94                         IntPtr hwnd_win=FindWindow(null, dgv_programlist.Rows[row].Cells[0].Value.ToString());
 95                         if(hwnd_win!=IntPtr.Zero) this.dosomething(hwnd_win,dgv_programlist.Rows[row].Cells[0].Value.ToString(),
 96                                                                    dgv_programlist.Rows[row].Cells[1].Value.ToString());
 97                     }catch(Exception e){
 98                         MessageBox.Show(e.Message,"提示:");
 99                     }
100                 }
101                 
102                 Thread.Sleep(Config.SleepTime);
103                 GC.Collect();
104             }
105         }
106         
107         private void dosomething(IntPtr hwnd_win,string programname,string buttonname)
108         {
109             const int BM_CLICK = 0x00F5;
110             try{
111                 IntPtr hwnd_button=FindWindowEx(hwnd_win, IntPtr.Zero, null,buttonname);
112                 if(hwnd_button!=IntPtr.Zero)
113                 {
114                     if(chk_getdeskshot.Checked) Config.GetDeskTop();
115                     Message msg = Message.Create(hwnd_button, BM_CLICK, new IntPtr(0), new IntPtr(0));
116                     PostMessage(msg.HWnd, msg.Msg, msg.WParam, msg.LParam);
117                     this.WriteLog(programname,buttonname);
118                 }
119             }catch(Exception e){
120                 MessageBox.Show(e.Message,"提示:");
121             }
122         }
123         
124         private void LoadConfig()
125         {
126             if(File.Exists(Config.ConfigFile))
127             {
128                 FileStream fs=new FileStream(Config.ConfigFile, FileMode.Open);
129                 StreamReader sr=new StreamReader(fs,Encoding.Default);
130                 while(!sr.EndOfStream)
131                 {
132                     string[] sline=sr.ReadLine().Split('>');
133                     if(sline.Length==3||sline.Length==4)
134                     {
135                         if(sline[0]=="SleepTime")
136                         {
137                             Config.SleepTime=Convert.ToInt32(sline[1]);
138                         }else if(sline[0]=="AutoGetDeskshot")
139                         {
140                             chk_getdeskshot.Checked=bool.Parse(sline[1]);
141                         }
142                         else if(sline[0]=="Program")
143                         {
144                             dgv_programlist.Rows.Add(new string[]{sline[1],sline[2]});
145                         }
146                     }
147                 }
148                 sr.Close();
149                 fs.Close();
150                 sr.Dispose();
151                 fs.Dispose();
152             }else{
153                 MessageBox.Show("没有找到程序的配置文件'EEPConfig.ini',程序无法正常运行.","提示:");
154                 File.Create(Config.ConfigFile);
155                 Application.Exit();
156             }
157         }
158         
159         private void WriteLog(string programname,string dosomething)
160         {
161             FileStream fs;
162             if(File.Exists(Config.LogFile))
163             {
164                 fs=new FileStream(Config.LogFile, FileMode.Append);
165             }else{
166                 fs=new FileStream(Config.LogFile, FileMode.CreateNew);
167             }
168             StreamWriter sw=new StreamWriter(fs,Encoding.Default);
169             sw.WriteLine(string.Format("{0} 检测到{1}异常,执行'{2}'",DateTime.Now.ToString(),programname,dosomething));
170             sw.Close();
171             fs.Close();
172             sw.Dispose();
173             fs.Dispose();
174         }
175         
176         void Programlist_menu_deleteClick(object sender, EventArgs e)
177         {
178             dgv_programlist.Rows.RemoveAt(dgv_programlist.SelectedRows[0].Index);
179             btn_applyandsave.Enabled=true;
180         }
181         
182         void Programlist_menuOpening(object sender, System.ComponentModel.CancelEventArgs e)
183         {
184             programlist_menu_delete.Enabled=dgv_programlist.SelectedRows.Count>0?true:false;
185         }
186         
187         void Txt_dosomethingTextChanged(object sender, EventArgs e)
188         {
189             btn_add.Enabled=txt_programname.Text!=""&&txt_dosomething.Text!=""?true:false;
190         }
191         
192         void Btn_addClick(object sender, EventArgs e)
193         {
194             dgv_programlist.Rows.Add(new string[]{txt_programname.Text,txt_dosomething.Text});
195             txt_programname.Clear();
196             txt_dosomething.Clear();
197             btn_applyandsave.Enabled=true;
198         }
199         
200         void Btn_applyandsaveClick(object sender, EventArgs e)
201         {
202             FileStream fs=new FileStream(Config.ConfigFile, FileMode.Truncate);
203             StreamWriter sw=new StreamWriter(fs,Encoding.Default);
204             sw.WriteLine(string.Format("SleepTime>{0}>",Config.SleepTime/1000));
205             sw.WriteLine(string.Format("AutoGetDeskshot>{0}>",chk_getdeskshot.Checked.ToString()));
206             for(int row=0;row<dgv_programlist.Rows.Count;row++)
207             {
208                 sw.WriteLine(string.Format("Program>{0}>{1}>",dgv_programlist.Rows[row].Cells[0].Value.ToString(),dgv_programlist.Rows[row].Cells[1].Value.ToString()));
209             }
210             sw.Flush();
211             sw.Close();
212             fs.Close();
213             sw.Dispose();
214             fs.Dispose();
215             btn_applyandsave.Enabled=false;
216         }
217         
218         private void HideForm()
219         {
220             this.Visible=false;
221             this.ShowInTaskbar=false;
222             this.Hide();
223         }
224         
225         private void ShowForm()
226         {
227             this.Visible=true;
228             this.ShowInTaskbar=true;
229             this.WindowState= FormWindowState.Normal;
230             this.Show();
231         }
232         
233         private void Exit()
234         {
235             this.HideForm();
236             this.Stop();
237             Application.Exit();
238         }
239         
240         void Notify_menu_exitClick(object sender, EventArgs e)
241         {
242             this.Exit();
243         }
244         
245         void NotifyMouseClick(object sender, MouseEventArgs e)
246         {
247             if(e.Button== MouseButtons.Left)
248             {
249                 if(this.Visible)
250                 {
251                     this.HideForm();
252                 }else{
253                     this.ShowForm();
254                 }
255             }
256         }
257         
258         void Btn_miniClick(object sender, EventArgs e)
259         {
260             this.HideForm();
261         }
262         
263         void Notify_menu_showwindowClick(object sender, EventArgs e)
264         {
265             this.ShowForm();
266         }
267         
268         void Chk_getdeskshotCheckedChanged(object sender, EventArgs e)
269         {
270             btn_applyandsave.Enabled=true;
271         }
272     }
273 }

 

posted on 2012-09-22 09:52  HappyCode.老K  阅读(408)  评论(6)    收藏  举报