我有一个 C# WinForms 应用程序。当在启动主 UI 表单之前显示 DevExpress XtraMessageBox 时,静态 void Main() 方法中会引发此异常。以下是代码(简化):
static void Main(string[] args)
{
// Display Splash Screen.
SplashForm.Start();
if (!CheckLicense())
XtraMessageBox.Show(null, "Not Licensed!", "License Check",
MessageBoxButtons.OK, MessageBoxIcon.Information);
using (MainForm form = new MainForm())
{
SplashForm.Stop();
if (form != null)
Application.Run(form);
}
}
虽然它是一个 DevExpress 控件,但实际上在调用以下命令时会引发异常:
System.Drawing.Graphics.get_PageUnit()
异常不会始终如一地抛出。它可以在特定机器上重现,但是一旦我在异常之前添加一个 MicroSoft MessageBox.Show() 以显示调试信息,那么我就不再得到异常。这是堆栈跟踪:
Object is currently in use elsewhere.
at System.Drawing.Graphics.get_PageUnit()
at DevExpress.Utils.Text.FontsCache.GetFontCacheByFont(Graphics graphics, Font font)
at DevExpress.Utils.Text.FontsCache.GetStringSize(Graphics graphics, String text, Font font, StringFormat stringFormat, Int32 maxWidth)
at DevExpress.Utils.Text.TextUtils.GetStringSize(Graphics g, String text, Font font, StringFormat stringFormat, Int32 maxWidth)
at DevExpress.Utils.Paint.XPaintMixed.CalcTextSize(Graphics g, String s, Font font, StringFormat strFormat, Int32 maxWidth)
at DevExpress.Utils.AppearanceObject.CalcTextSize(Graphics g, StringFormat sf, String s, Int32 width)
at DevExpress.Utils.AppearanceObject.CalcTextSize(Graphics g, String s, Int32 width)
at DevExpress.XtraEditors.Drawing.EditorButtonPainter.CalcCaptionSize(EditorButtonObjectInfoArgs e)
at DevExpress.XtraEditors.Drawing.EditorButtonPainter.CalcObjectMinBounds(ObjectInfoArgs e)
at DevExpress.XtraEditors.Drawing.SkinEditorButtonPainter.CalcObjectMinBounds(ObjectInfoArgs e)
at DevExpress.XtraEditors.ViewInfo.BaseButtonViewInfo.CalcBestFit(Graphics g)
at DevExpress.XtraEditors.BaseControl.CalcBestSize()
at DevExpress.XtraEditors.XtraMessageBoxForm.CreateButtons()
at DevExpress.XtraEditors.XtraMessageBoxForm.ShowMessageBoxDialog()
at DevExpress.XtraEditors.XtraMessageBoxForm.ShowMessageBoxDialog(XtraMessageBoxArgs message)
at DevExpress.XtraEditors.XtraMessageBox.Show(UserLookAndFeel lookAndFeel, IWin32Window owner, String text, String caption, DialogResult[] buttons, Icon icon, Int32 defaultButton, MessageBoxIcon messageBeepSound)
at DevExpress.XtraEditors.XtraMessageBox.Show(IWin32Window owner, String text, String caption, DialogResult[] buttons, Icon icon, Int32 defaultButton, MessageBoxIcon messageBeepSound)
at DevExpress.XtraEditors.XtraMessageBox.Show(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton)
at DevExpress.XtraEditors.XtraMessageBox.Show(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon)
at Test.Program.Main(String[] args)
更新: 我通过确保在执行任何 UI 工作之前执行 Application.Run() 来解决它。以这种方式启动消息循环/泵。我现在让 Application.Run() 启动启动画面,它轻量级且快速。然后我从启动表单中实例化主表单,激活它并隐藏启动表单。