我使用此代码来捕获 WinForm 应用程序 UnhandledException。
[STAThread]
static void Main(string[] args)
{
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new
System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
// Set the unhandled exception mode to force all Windows Forms errors
// to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
try
{
Application.Run(new MainForm());
} catch....
在那里我将尝试重新启动应用程序。现在我的问题是模拟这样的异常。我在尝试之前尝试过(主要):throw new NullReferenceException("test");
VS抓住了它。
在 MainForm 代码中也尝试了 button :
private void button1_Click(object sender, EventArgs ev)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(TestMe), null);
}
protected void TestMe(object state)
{
string s = state.ToString();
}
没有帮助,VS 抓住了它,即使在发布模式下也是如此。
- 最后,我应该如何强制应用程序生成
UnhandleldException
? - 我可以重新启动应用程序
CurrentDomain_UnhandledException
吗? - 我怎样才能生成一个
ThreadException
?
PS。
如果我在 VS 之外启动一个 Windows 通用窗口
应用程序 MyApplication”遇到错误,应关闭...blabla...发送报告/不发送。
但是,我希望 VS 输入此方法(...Domain_Unhahdled...)
编辑:重新启动应用程序时,是否可以禁用 Windows 崩溃消息,如下所示: alt text http://byfiles.storage.msn.com/y1pOhWnAAXfMYtJH2VNa5iL0l1hjAqNHD2VmVnl8nN6L1oQC_xHkyHCJxhMc1ZLxLOH9ZXfZoo5zX8?PARTNER=WRITER ?
代码:
static void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)
{
// Since we can't prevent the app from terminating
// log this to the event log.
Logger.LogMessage(ERROR, errorMsg);
Application.Restart();