使用Process类运行程序

来源:互联网 发布:脂肪型眼袋 知乎 编辑:程序博客网 时间:2024/05/21 14:06

只有在STA线程上ShellExecute 才能确保工作无误。在Process的实现中,并没有考虑到这个问题,所以使用Process类运行ShellExecute可能会出错。如果你不能保证调用Process.Start的线程的ApartmentState,可以使用如下的代码来避免这个问题:

 

using System;

using System.Threading;

public class Foo {

    public static void OpenUrl()    {

        System.Diagnostics.Process.Start(@"http://www.google.com");

    }

 

    public static void Main() {

        ThreadStart openUrlDelegate = new ThreadStart(Foo.OpenUrl);

        Thread myThread = new Thread(openUrlDelegate);

        myThread.SetApartmentState(ApartmentState.STA);   

        myThread.Start();

        myThread.Join();

    }

}

在使用Process类来打开未知类型文件时,会得到错误代码为ERROR_NO_ASSOCIATION Win32Exception

设置ProcessStartInfo中的ErrorDialog可以显示“Open With”对话框:

using System.Diagnostics;

 

class Test {

   public static void Main() {

       ProcessStartInfo info = new ProcessStartInfo();

       info.FileName = "t.tt";   

       info.ErrorDialog = true;

       Process.Start(info);

   }

}

原创粉丝点击