为什么我'm得到win32异常错误退出我的应用程序

本文关键字:错误 异常 退出 我的 应用程序 win32 得到 为什么 | 更新日期: 2023-09-27 18:16:26

在Form1关闭事件中,当选择YES关闭应用程序时,有时会出现异常:

Environment.Exit(0);

这是Form1关闭事件代码:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {    
            if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                e.Cancel = true;
            }
            else
            {
                e.Cancel = false;
                Environment.Exit(0);
            }

        }

异常:创建窗口句柄错误

这是完整的异常错误消息:

System.ComponentModel.Win32Exception was unhandled
  HResult=-2147467259
  Message=Error creating window handle.
  Source=System.Windows.Forms
  ErrorCode=-2147467259
  NativeErrorCode=1406
  StackTrace:
       at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
       at System.Windows.Forms.Control.CreateHandle()
       at System.Windows.Forms.Control.get_Handle()
       at System.Windows.Forms.VisualStyles.VisualStyleRenderer.DrawParentBackground(IDeviceContext dc, Rectangle bounds, Control childControl)
       at System.Windows.Forms.ButtonInternal.ButtonStandardAdapter.PaintThemedButtonBackground(PaintEventArgs e, Rectangle bounds, Boolean up)
       at System.Windows.Forms.ButtonInternal.ButtonStandardAdapter.PaintWorker(PaintEventArgs e, Boolean up, CheckState state)
       at System.Windows.Forms.ButtonInternal.ButtonStandardAdapter.PaintUp(PaintEventArgs e, CheckState state)
       at System.Windows.Forms.ButtonInternal.ButtonBaseAdapter.Paint(PaintEventArgs pevent)
       at System.Windows.Forms.ButtonBase.OnPaint(PaintEventArgs pevent)
       at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
       at System.Windows.Forms.Control.WmPaint(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  InnerException: 

也许我需要释放/关闭/处理一些我没有的东西?

有时异常显示,但有时没有,现在我试图关闭应用程序,像5次在一排没有任何异常

为什么我'm得到win32异常错误退出我的应用程序

您实际上并不需要else条件-如果他们选择'no',您只需允许表单关闭。我能看到调用Environment.Exit(0)的唯一明显原因是当您有非模态形式(或其他进程)时,您也想/需要关闭。最好是循环遍历子表单并触发它们的关闭事件。我曾经这样写过:

// Close each child window of this form
foreach ( Window window in Application.Current.Windows )
{
    if ( window != null && window.Owner == this )
    {
        window.Close();
    }
}

已经有一段时间了,但我相信你必须在创建表单时手动分配Owner属性。

当然,您可能有其他完全合理的理由调用Environment.Exit(0)