1

这是代码:

private void processNotePad_Exited(object sender, EventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                View_Log_File.Enabled = true;
            });
        }

在 Form1 中,我有一个菜单,我单击它并在那里打开一个新表单,我有一个按钮单击,使用 notepad.exe 打开一个日志文件(txt 文件)如果我先关闭记事本然后关闭菜单表单,一切正常。但是,如果我首先关闭菜单表单,然后在尝试关闭记事本后,我会遇到异常:

异常错误是:在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke

System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
       at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
       at System.Windows.Forms.Control.Invoke(Delegate method)
       at mws.SettingsMenu.processNotePad_Exited(Object sender, EventArgs e) in D:\C-Sharp\Download File\Downloading-File-Project-Version-012\Downloading File\SettingsMenu.cs:line 148
       at System.Diagnostics.Process.OnExited()
       at System.Diagnostics.Process.RaiseOnExited()
       at System.Diagnostics.Process.CompletionCallback(Object context, Boolean wasSignaled)
       at System.Threading._ThreadPoolWaitOrTimerCallback.WaitOrTimerCallback_Context(Object state, Boolean timedOut)
       at System.Threading._ThreadPoolWaitOrTimerCallback.WaitOrTimerCallback_Context_f(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading._ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback(Object state, Boolean timedOut)
  InnerException: 

在这种情况下我应该如何照顾?如果用户先关闭菜单表单,然后关闭记事本,则会抛出此异常。

4

1 回答 1

1

由于如果在记事本窗口之前关闭菜单窗体会出现错误,我建议您在菜单窗体关闭之前使用菜单窗体FormClosing EventHandler关闭记事本窗口。

从上面的链接:

FormClosing 事件在窗体被关闭时发生。当表单关闭时,它会被释放,释放与表单相关的所有资源。如果您取消此事件,表单将保持打开状态。要取消关闭窗体,请将传递给事件处理程序的 FormClosingEventArgs 的 Cancel 属性设置为 true。

于 2013-01-04T04:27:28.640 回答