天天看点

C# 外部组件发生异常原因分析 [分析]

在项目中,用From2 启动 Report 正常,用From1 启动 Report 失败,日志:

2007-05-12 13:11:06

StartGenerateReportTask: System.Runtime.InteropServices.SEHException: 外部组件发生异常。

   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)

   at System.Windows.Forms.ComponentManager.System.Windows.Forms.UnsafeNativeMethods+IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)

   at System.Windows.Forms.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)

   at System.Windows.Forms.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)

   at System.Windows.Forms.Application.RunDialog(Form form)

   at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)

   at System.Windows.Forms.Form.ShowDialog()

   at ZTE.CCG.Report.ReportController.StartGenerateReportTask(String contractHeader) in ***/report/quotationgenerationmodule/reportcontroller.cs:line 469

由于From2 和 Report 是同一个人开发的,直接启动 ReportController 是没有问题的,而我们自己通过相同的方法启动 ReportController 就出现了问题。开始以为是我们程序那里出现了问题,跟踪代码发现这个异常不固定,很难确定是那里出现了问题。

虽然显示的外部组建发生异常,可应用程序中没有调用任何其他的第三方应用程序哦。

对比Form1 和Form2 发现:

Form1:

        [STAThread]

        public static void Main(string[] args)

        {

           // lots of code...

           // it's same of the code posted on Form2.

        }

Form2:

                Application.EnableVisualStyles();

                Application.DoEvent();

更改Form1中的代码继续执行,程序正常执行,没有任何错误。

取消 那两句话,错误又再次出现。

再查询了一下MSDN ,发现 :

“此方法启用应用程序的 Windows XP 可视化样式。如果控件和操作系统支持可视化样式,则控件将以这种样式进行绘制。若要使 EnableVisualStyles 生效,必须在应用程序中创建任何控件之前调用它;EnableVisualStyles 通常是 Main 函数的第一行。当调用 EnableVisualStyles 时,无需单独的清单即可启用可视化样式。

对于支持 FlatStyle 属性的控件,请确保将 FlatStyle 属性设置为 FlatStyle.System 值。”

搜索 FlatStyle ,发现在 Report 里面很多自定义控件这么写的:

this.xxxControlName.FlatStyle = System.Windows.Form.FlatStyle.System;

也就是说,控件是使用的系统的样式。在使用系统样式的时候必须告诉系统启用虚拟样式。

否则可能出现上述应用程序异常。

为了验证,这个猜想,在From1 中注释掉:

Application.EnableVisualStyles();

Application.DoEvent();

果然程序执行时回出现异常。

在google 上搜索了一下,发现很多上述类似异常的都或多或少提及到XP 样式了。

相关资源:

1).NET 1.1 Framework Fix:

<a href="http://support.microsoft.com/Default.aspx?kbid=899511">http://support.microsoft.com/Default.aspx?kbid=899511</a>

2)VS2005 中解决方法:

<a href="http://support.microsoft.com/kb/897298">http://support.microsoft.com/kb/897298</a>

<a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=48878&amp;SiteID=1">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=48878&amp;SiteID=1</a>

<a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=388724&amp;SiteID=1">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=388724&amp;SiteID=1</a>

继续阅读