顯示具有 處理程序 標籤的文章。 顯示所有文章
顯示具有 處理程序 標籤的文章。 顯示所有文章

2010年12月31日 星期五

監視一個處理程序

using System;
using System.Windows.Forms;

namespace DevDistrict.MachineMonitor
{
 public class Monitor
 {
  [STAThread()]
  public static void Main()
  {
   System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName("Notepad");

   if (p.Length<0)
   {
    Console.WriteLine("No process");
    return;
   }

   if (p[0].HasExited)
   {
    Console.WriteLine("Process Exited");
    return;
   }

   p[0].Exited+=new EventHandler(Startup_Exited);

   while(!p[0].HasExited)
   {
    p[0].WaitForExit(30000);
    Console.WriteLine("checking process health");
   }
  }

  private static void Startup_Exited(object sender, EventArgs e)
  {
   Console.WriteLine("PROCESS EXIT CAUGHT");
  }
 }
}

2010年12月30日 星期四

檢查指定檔案是否正在被處理程序使用

檢查指定檔案是否正在被處理程序使用。
程式碼
public static bool CheckIfFileIsBeingUsed(string fileName)
{
FileStream s = null;
try
{
s=new FileStream (fileName, FileMode.Open, FileAccess.Read, FileShare.Delete );
return false;
}
catch (System.IO.IOException)
{
return true;
}
finally
{
if (s != null)
s.Close();
}
}

結束處理程序

指令處理程序名稱,結束該處理程序。
如何使用?"KillProcess ( "outlook" );"
程式碼
private void KillProcess ( string processName )
{
System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName ( processName );

foreach ( System.Diagnostics.Process procCur in procs )
{
//procCur.CloseMainWindow();
procCur.Kill ( );
procCur.Close ( );
}
}

啟動外部應用程式

開啟Notepad應用程式,編輯檔案test.dat。
程式碼
using System;
using System.Diagnostics ;

public class Sample
{
public static void Main()
{
Process pr = new Process();
pr.StartInfo.FileName = "Notepad.exe";
pr.StartInfo.Arguments = "test.dat";
pr.Start();

while (pr.HasExited == false)
if ((DateTime.Now.Second % 5) == 0)
{ // 每五秒顯示一個tick。
Console.Write(".");
System.Threading.Thread.Sleep(1000);
}
}
}

等待應用程式執行結束,並取得應用程式輸出字串。
程式碼
using System.Diagnostics;
private bool CommandLine(string args)
{
ProcessStartInfo proc = null ;
Process p=null ;
string res;
try
{
proc = new ProcessStartInfo(); // a process holder 

proc.FileName = "cmd.exe";
proc.CreateNoWindow = true;
proc.RedirectStandardInput = false;
proc.RedirectStandardOutput = true;

proc.Arguments = "/k "+args;
proc.UseShellExecute = false; /*do not show console for the process - a must*/

p = Process.Start(proc);

res = p.StandardOutput.ReadToEnd();
Output(res);
p.WaitForExit(); /*wait indefinitely for the associated process to exit*/
return true;
}
catch (Exception Ex)
{
Output (QONSOLE + ": " + Ex.Message);
return false;
}
finally
{
if (p != null) p.Close();
}
}

列出所有的處理程序

列出所有的處理程序
程式碼
private void ShowAllProcess()
{
List dd = new List();
foreach (System.Diagnostics.Process procCur in System.Diagnostics.Process.GetProcesses())
{
dd.Add(procCur.ProcessName);
}
//排序後將所以的處裡程序名稱印出
dd.Sort(delegate(string s1, string s2) { return s1.CompareTo(s2); });
dd.ForEach(delegate(string s1) { Console.WriteLine(s1); });
Console.WriteLine(dd.Count);
}