抓住另一个进程未处理的exception

我想知道我是否可以捕获由我开始使用Process.Start(…)的另一个进程抛出的未处理的exception

我知道我可以使用此链接捕获standered错误,但我想要的是捕获通常由.NET环境的Just In Time调试器捕获的错误,该窗口包含以下单词:“发生了未处理的exception在你的应用程序中。如果你继续,应用程序将忽略此错误并尝试继续。如果你单击退出,应用程序将立即关闭….“然后是exception消息,然后是”继续“, “退出”按钮。

提前致谢。

如果您正在调用.Net可执行程序集,则可以加载它并(由您自己承担风险:D)将Program类的Main方法调用到try_catch语句中:

Assembly assembly = Assembly.LoadFrom("ErroneusApp.exe"); Type[] types= assembly.GetTypes(); foreach (Type t in types) { MethodInfo method = t.GetMethod("Main", BindingFlags.Static | BindingFlags.NonPublic); if (method != null) { try { method.Invoke(null, null); } catch (Exception ex) { Console.WriteLine(ex.Message); } break; } } 

但请注意您所介绍的安全风险。

你可以尝试类似的东西来避免出现调试器问题,你不会得到例外但只有退出代码:

 class Program { static void Main(string[] args) { try { ProcessStartInfo info = new ProcessStartInfo("ErroneusApp.exe"); info.ErrorDialog = false; info.RedirectStandardError = true; info.RedirectStandardOutput = true; info.CreateNoWindow = true; info.UseShellExecute = false; System.Diagnostics.Process p = System.Diagnostics.Process.Start(info); p.EnableRaisingEvents = true; p.Exited += p_Exited; } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } static void p_Exited(object sender, EventArgs e) { Process p = sender as Process; if (p != null) { Console.WriteLine("Exited with code:{0} ", p.ExitCode); } else Console.WriteLine("exited"); } } 

在这个问题中,他们为此提供了另一种解决方法,但更改了一些注册表值。

不可以。如果受控应用程序使用standardError和返回代码,您可能会收到错误或exception的通知,但您无法以任何方式捕获它。

您可以简单地在新域中执行程序集,而不是像在jmservera的答案中那样尝试查找Main方法。 请参阅此msdn文章

在解决之前的目标调用问题时,我最终得到了以下方法。

您的某些应用程序将在当前目录中具有依赖项,这会导致在另一个目录中执行时出现exception,因为依赖项不匹配。

 Assembly assembly = Assembly.LoadFrom(file); Directory.SetCurrentDirectory(Path.GetDirectoryName(file)); Type[] types = assembly.GetTypes(); foreach (Type t in types) { MethodInfo method = t.GetMethod("Main", BindingFlags.Static | BindingFlags.NonPublic); if (method != null) { try { method.Invoke(null, null); } 

Directory.SetCurrentDirectory(Path.GetDirectoryName(文件)); //通过引用当前目录,将解析目标调用exception。