执行程序后关闭当前表单(在C#中) [英] Close current form after execute a procee(in C# )

查看:58
本文介绍了执行程序后关闭当前表单(在C#中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


在我用c#设计的应用程序中,我想在我的表单中执行计算器。

但是当通过以下命令调用它时,当前表单将被关闭。 br />
流程ie = Process.Start(calc.exe);



如何执行此操作,以便当前表单保持打开状态?

非常感谢

Hi In my application which designed by c#, I want to execute calculator in my form .
But when it be called by following command, the current form will be closed.
Process ie = Process.Start("calc.exe");

How can I do this, so that current form remain open?
Thanks very much

推荐答案

您可以通过调用创建一个单独的线程并等待进程终止ie.WaitForExit()

http:/ /msdn.microsoft.com/en-us/library/fb4aw7b8.aspx [ ^ ]。



此等待将使您的线程处于等待状态。该线程将被切换出来,并且在被唤醒之前不会被安排回执行,因此该线程在等待时将占用零CPU时间。当进程终止时,它将被唤醒。其他条件尤其包括超时或线程中止。



当线程被唤醒时,您可以使用 Window.Close关闭窗口()。但是怎么样?



问题是:你不能从非UI线程中调用与UI相关的任何东西。相反,您需要使用 Invoke System.Windows.Threading的方法。 Dispatcher (对于Forms或WPF)或 System.Windows.Forms.Control (仅限表单)。



您将在我过去的答案中找到有关其工作原理和代码示例的详细说明:

Control.Invoke()与Control.BeginInvoke() [ ^ ],

使用Treeview扫描仪和MD5的问题 [ ^ ]。



另请参阅有关线程的更多参考资料:

如何让keydown事件在不同的操作上运行vb.net中的线程 [ ^ ],

在启用禁用+多线程后控制事件未触发 [ ^ ]。



-SA
You can create a separate thread and wait for the process termination in it by calling ie.WaitForExit():
http://msdn.microsoft.com/en-us/library/fb4aw7b8.aspx[^].

This wait will put your thread in a wait state. The thread will be switched out and won''t be scheduled back to execution until it is waken up, so the thread will take zero CPU time while waiting. It will be waken up when the process is terminated. Other condition include, in particular, timeout or thread abortion.

When the thread is waken up, you can close your window using Window.Close(). But how?

The problem is: you cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA


这篇关于执行程序后关闭当前表单(在C#中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆