InvalidOperationException
如果操作无法完成,您将收到一条消息。在您的代码中,您可能会在调用orInvalidOperationException
之前收到进程是否已退出的信息。myProcess.Kill();
myProcess.CloseMainWindow();
当一个进程已经退出时,你不能杀死它。要解决此问题,请避免在线程空闲时关闭进程。您可以在执行命令之前捕获异常或检查进程是否已退出。
例子
class MyProcess
{
public static void Main()
{
Process myProcess = new Process(); //Initialize a new Process of name myProcess
ProcessStartInfo ps = new ProcessStartInfo(); //Initialize a new ProcessStartInfo of name ps
try
{
ps.FileName = @"IExplore.exe"; //Set the target file name to IExplore.exe
ps.WindowStyle = ProcessWindowStyle.Normal; //Set the window state when the process is started to Normal
myProcess.StartInfo = ps; //Associate the properties to pass to myProcess.Start() from ps
myProcess.Start(); //Start the process
}
catch (Exception e)
{
Console.WriteLine(e.Message); //Write the exception message
}
Thread.Sleep(3000); //Stop responding for 3 seconds
if (myProcess.HasExited) //Continue if the process has exited
{
//The process has exited
//Console.WriteLine("The process has exited");
}
else //Continue if the process has not exited
{
//myProcess.CloseMainWindow(); //Close the main Window
myProcess.Kill(); //Terminate the process
}
Console.WriteLine("press [enter] to exit"); //Writes press [enter] to exit
Console.Read(); //Waits for user input
}
}
注意:如果您运行的是 IE8,您可能会注意到 Internet Explorer 8 已实现更改,其中多个打开的浏览器窗口或框架在所有打开的选项卡和窗口(包括用户打开的新 IE 框架窗口)中共享相同的会话 cookie。
您可以使用参数-nomerge运行进程IExplore.exe以运行新的 IE8 窗口会话,并避免将您创建的新进程与之前创建的进程合并(由 IE8 创建的默认进程与其他进程合并)。因此,拥有一个可以从应用程序控制的新进程,而不是由 IE8 创建的进程。
例子
Process myProcess = new Process(); //Initialize a new Process of name myProcess
ProcessStartInfo ps = new ProcessStartInfo(); //Initialize a new ProcessStartInfo of name ps
try
{
ps.FileName = @"IExplore.exe"; //Set the target file name to IExplore.exe
ps.Arguments = "-nomerge";
ps.WindowStyle = ProcessWindowStyle.Normal; //Set the window state when the process is started to Normal
myProcess.StartInfo = ps; //Associate the properties to pass to myProcess.Start() from ps
myProcess.Start(); //Start the process
}
catch (Exception e)
{
Console.WriteLine(e.Message); //Write the exception message
}
Thread.Sleep(3000); //Stop responding for 3 seconds
if (myProcess.HasExited) //Continue if the process has exited
{
//The process has exited
//Console.WriteLine("The process has exited");
}
else //Continue if the process has not exited; evaluated if the process was not exited.
{
myProcess.Kill(); //Terminate the process
}
-1
此外,如果 IE8 的进程意外终止,1
如果它被用户终止,并且0
如果退出将控制权传递给另一个实例,则进程退出代码将等于。
谢谢,
我希望你觉得这有帮助:)