当关闭记事本进程时我得到异常为什么会这样?

时间:2013-01-04 03:34:42

标签: c#

这是代码:

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: 

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

1 个答案:

答案 0 :(得分:1)

如果在NotePad窗口之前关闭菜单表单时出错,我建议您在菜单表单关闭之前使用菜单表单FormClosing EventHandler关闭NotePad窗口。

从上面链接:

  

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