C# 之進程操作

 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 //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();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章