C#启动一个外部程序的多种方法

先引用命名空间:using System.Diagnostics;

小例:

//在现有窗口中打开baidu

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

//在新窗口中打开baidu
using System.Diagnostics;
Process ps=new Process();
string yourURL="http://www.baidu.com
";
ps.StartInfo.FileName="iexplore.exe";
ps.StartInfo.Arguments=yourURL;
ps.Start();

1.process类的使用

Start 启动进程资源将其与process类关联

Kill立即关闭进程

waitforExit 在等待关联进程的退出

Close 释放与此关联的所有进程

/*
* Created by SharpDevelop.
* User: Administrator
* Date: 2007-6-17
* Time: 16:20
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
//process类的名空间
using System.Diagnostics;

namespace process
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm
{
   [STAThread]
   public static void Main(string[] args)
   {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
   }
  
   public MainForm()
   {
    //
    // The InitializeComponent() call is required for Windows Forms designer support.
    //
    InitializeComponent();
   
    //
    // TODO: Add constructor code after the InitializeComponent() call.
    //
   }
   //启动IE主页http://www.baidu.com/
   void Button1Click(object sender, System.EventArgs e)
   {
    Process.Start("IExplore.exe","http://www.baidu.com/");
   }
   //启动资源管理器
   void Button2Click(object sender, System.EventArgs e)
   {
    Process.Start("explorer.exe");
   }
   //启动office中的EXCEl
   void Button3Click(object sender, System.EventArgs e)
   {
    Process.Start("EXCEL.exe");
   }
   //启动WINDOWS播放器
   void Button4Click(object sender, System.EventArgs e)
   {
    Process.Start("dvdplay.exe");
   }
}
}
源码下载:http://download.csdn.net/source/195507

http://download1.csdn.net/down3/20070617/17164940911.rar 用C#来实现相同的效果,发现C#本身方便的进程线程机制使工作变得简单至极,随手记录一下。

2.首先,我们可以通过设置Process类,获取输出接口,代码如下:

     Process proc = new Process();
     proc .StartInfo.FileName = strScript;
     proc .StartInfo.WorkingDirectory = strDirectory;
     proc .StartInfo.CreateNoWindow = true;
     proc .StartInfo.UseShellExecute = false;
     proc .StartInfo.RedirectStandardOutput = true;
     proc .Start();

然后设置线程连续读取输出的字符串:

     eventOutput = new AutoResetEvent(false);
     AutoResetEvent[] events = new AutoResetEvent[1];
     events[0] = m_eventOutput;

     m_threadOutput = new Thread( new ThreadStart( DisplayOutput ) );
     m_threadOutput.Start();
     WaitHandle.WaitAll( events );

线程函数如下:

   private void DisplayOutput()
   {
    while ( m_procScript != null && !m_procScript.HasExited )
    {
     string strLine = null;
     while ( ( strLine = m_procScript.StandardOutput.ReadLine() ) != null)
     {
      m_txtOutput.AppendText( strLine + "/r/n" );
      m_txtOutput.SelectionStart = m_txtOutput.Text.Length;
      m_txtOutput.ScrollToCaret();
     }
     Thread.Sleep( 100 );
    }
    m_eventOutput.Set();
   }

这里要注意的是,使用以下语句使TextBox显示的总是最新添加的,而AppendText而不使用+=,是因为+=会造成整个TextBox的回显使得整个显示区域闪烁

     m_txtOutput.AppendText( strLine + "/r/n" );
     m_txtOutput.SelectionStart = m_txtOutput.Text.Length;
     m_txtOutput.ScrollToCaret();

为了不阻塞主线程,可以将整个过程放到一个另一个线程里就可以了

 

3.bat文件控制参数的方法:


将你的net use //172.16.17.1 /user:username password写到bat文件中,然后运行下面代码就可以了。
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.FileName = "d://netuse.bat";
            process.Start();

程序控制参数方法:

System.Diagnostics.ProcessStartInfo psi =
       new System.Diagnostics.ProcessStartInfo();
//prompt
psi.FileName = @"C:/WINDOWS/system32/cmd.exe"; // Path for the cmd prompt
psi.Arguments =@"net use //172.16.17.1 /user:username password";
psi.WindowStyle=System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process.Start(psi);
就是用进程启动cmd.exe

使用Process类运行ShellExecute的一个问题(点击查看引用)
只有在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();
    }
}

 

 

C#启动一个外部程序(1) 调用Win32 API。
1.
using  System.Runtime.InteropServices;
2.
[DllImport( " shell32.dll " )]
        
public   static   extern   int  ShellExecute(IntPtr hwnd,StringBuilder lpszOp,StringBuilder lpszFile,StringBuilder lpszParams,StringBuilder lpszDir, int  FsShowCmd);
3.调用,打开记事本:
int  a  =  ShellExecute(IntPtr.Zero,new StringBuilder("Open"),new StringBuilder("notepad"),new StringBuilder(""),new StringBuilder(@"C:/"), 1);
            System.Windows.Forms.MessageBox.Show(a.ToString());
4.打开一个网页:
ShellExecute(IntPtr.Zero, new  StringBuilder( " Open " ), new  StringBuilder( " http://yao.cnblogs.com/ " ), new  StringBuilder( "" ), new  StringBuilder( "" ),  1 );

ShellExecute函数原型及参数含义如下:

  function ShellExecute(hWnd: HWND; Operation, FileName, Parameters,Directory: PChar; ShowCmd: Integer): HINST; stdcall;

  ●hWnd:用于指定父窗口句柄。当函数调用过程出现错误时,它将作为Windows消息窗口的父窗口。例如,可以将其设置为应用程序主窗口句柄,即Application.Handle,也可以将其设置为桌面窗口句柄(用GetDesktopWindow函数获得)。

  ●Operation:用于指定要进行的操作。其中“open”操作表示执行由FileName参数指定的程序,或打开由FileName参数指定的文件或文件夹;“print”操作表示打印由FileName参数指定的文件;“explore”操作表示浏览由FileName参数指定的文件夹。当参数设为nil时,表示执行默认操作“open”。

  ●FileName:用于指定要打开的文件名、要执行的程序文件名或要浏览的文件夹名。

  ●Parameters:若FileName参数是一个可执行程序,则此参数指定命令行参数,否则此参数应为nil或PChar(0)。

  ●Directory:用于指定默认目录。

  ●ShowCmd:若FileName参数是一个可执行程序,则此参数指定程序窗口的初始显示方式,否则此参数应设置为0。此参数更详细说明见: C#启动一个外部程序(1) 

  若ShellExecute函数调用成功,则返回值为被执行程序的实例句柄。若返回值小于32,则表示出现错误。
  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值