C# 中可以操作系统当前的进程,Process类提供的是对正在计算机上运行的进程的访问,在这里要讨论到一个容易混淆的概念,进程和线程.简单的讲,进程就是计算机当前运行的应用程序,线程则是操作系统向进程分配处理器时间的基本单位.系统的进程在系统上由其进程标识符唯一标识.但是在Windows中,进程由其句柄标识,句柄在计算机上可能并不唯一,即使进程已退出,操作系统仍保持进程句柄,所以句柄泄漏比内存泄漏危害更大。

  下面介绍一下Process类的使用方法。

  1.process类的使用

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

Kill立即关闭进程

waitforExit 在等待关联进程的退出

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

 

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");
   }
}
}

用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 http://www.cnblogs.com/acis_/admin/file://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 mailto:=@%22net use http://www.cnblogs.com/acis_/admin/file://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();
    }
}

 

posted on 2009-07-19 04:33  阿C's  阅读(574)  评论(0编辑  收藏  举报