Csharp/C Sharp/Development Class/Process

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Build up a list of the running processes

 
using System;
using System.Collections.Generic;
using System.Diagnostics;
class MainClass {
    static void Main() {
        
        List<String> processes = new List<String>();
        foreach (Process process in Process.GetProcesses())
            processes.Add(process.ProcessName);
    }
}


CloseMainWindow,WaitForExit

 

using System;
using System.Threading;
using System.Diagnostics;
class MainClass
{
    public static void Main()
    {
        using (Process process = Process.Start("notepad.exe", @"c:\SomeFile.txt"))
        {
            Console.WriteLine("Waiting 5 seconds before terminating notepad.exe.");
            Thread.Sleep(5000);
            Console.WriteLine("Terminating Notepad with CloseMainWindow.");
            if (!process.CloseMainWindow())
            {
                Console.WriteLine("CloseMainWindow returned false - " + " terminating Notepad with Kill.");
                process.Kill();
            }
            else
            {
                if (!process.WaitForExit(2000))
                {
                    Console.WriteLine("CloseMainWindow failed to" + " terminate - terminating Notepad with Kill.");
                    process.Kill();
                }
            }
        }
    }
}


Detecting Process Completion

using System;
using System.Diagnostics;
public class DetectingProcessCompletion
{
    static void ProcessDone(object sender, EventArgs e)
    {
        Console.WriteLine("Process Exited");
    }
    
    public static void Main()
    {
        Process p = new Process();
        p.StartInfo.FileName = "notepad.exe";
        p.StartInfo.Arguments = "process3.cs";
        p.EnableRaisingEvents = true;
        p.Exited += new EventHandler(ProcessDone);
        p.Start();
        p.WaitForExit();
        Console.WriteLine("Back from WaitForExit()");
    }
}


Enum Modules For Pid

 
using System;
using System.Diagnostics;
class MainClass {
    static void Main(string[] args) {
        int pID = 12345;
        Process theProc;
        try { theProc = Process.GetProcessById(pID); } catch {
            Console.WriteLine("bad PID!");
            return;
        }
        Console.WriteLine("Here are the loaded modules for: {0}", theProc.ProcessName);
        try {
            ProcessModuleCollection theMods = theProc.Modules;
            foreach (ProcessModule pm in theMods) {
                Console.WriteLine(string.Format("-> Mod Name: {0}", pm.ModuleName));
            }
        } catch { Console.WriteLine("No mods!"); }
    }
}


Get current Process Name

 
using System;
using System.Reflection;
using System.Diagnostics;
class AssemType
{
  public static void Main(string[] args)
  {
    Process p = Process.GetCurrentProcess();
    string assemblyName = p.ProcessName + ".exe";
    Console.WriteLine("Examining : {0}", assemblyName);
    Assembly a = Assembly.LoadFrom(assemblyName);
    Type[] types = a.GetTypes();
    foreach(Type t in types)
    {
      Console.WriteLine("\nType : {0}",t.FullName);
      Console.WriteLine("\tBase class : {0}",t.BaseType.FullName);
    }
  }
}


Get Process property

using System;
using System.Diagnostics;
public class GetProc
{
   public static void Main()
   {
      Process thisProc = Process.GetCurrentProcess();
      string procName = thisProc.ProcessName;
      DateTime started = thisProc.StartTime;
      int procID = thisProc.Id;
      int memory = thisProc.VirtualMemorySize;
      int priMemory = thisProc.PrivateMemorySize;
      int physMemory = thisProc.WorkingSet;
      int priority = thisProc.BasePriority;
      ProcessPriorityClass priClass = thisProc.PriorityClass;
      TimeSpan cpuTime = thisProc.TotalProcessorTime;

      Console.WriteLine("Process: {0}, ID: {1}", procName, procID);
      Console.WriteLine("    started: {0}", started.ToString());
      Console.WriteLine("    CPU time: {0}", cpuTime.ToString());
      Console.WriteLine("    priority class: {0}  priority: {1}", priClass, priority);
      Console.WriteLine("    virtual memory: {0}", memory);
      Console.WriteLine("    private memory: {0}", priMemory);
      Console.WriteLine("    physical memory: {0}", physMemory);
      Console.WriteLine("\n    trying to change priority...");
      thisProc.PriorityClass = ProcessPriorityClass.High;
      priClass = thisProc.PriorityClass;
      Console.WriteLine("    new priority class: {0}", priClass);
   }
}


Get Threads

using System;
using System.Diagnostics;
public class GetThreads {
   public static void Main()
   {
      Process thisProc = Process.GetCurrentProcess();
      ProcessThreadCollection myThreads = thisProc.Threads;
      foreach(ProcessThread pt in myThreads)
      {
         DateTime startTime = pt.StartTime;
         TimeSpan cpuTime = pt.TotalProcessorTime;
         int priority = pt.BasePriority;
         ThreadState ts = pt.ThreadState;
         Console.WriteLine("thread:  {0}", pt.Id);
         Console.WriteLine("    started: {0}", startTime.ToString());
         Console.WriteLine("    CPU time: {0}", cpuTime);
         Console.WriteLine("    priority: {0}", priority);
         Console.WriteLine("    thread state: {0}", ts.ToString()); 
      }
   }
}


Input Output:Starting Processes

using System.Diagnostics;
public class StartingProcesses
{
    public static void Main()
    {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = "notepad.exe";
        startInfo.Arguments = "process.cs";
        
        Process.Start(startInfo);
    }
}


Listing all threads for a process inn a ListView

 

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
public class Form1 : System.Windows.Forms.Form {
    private System.Windows.Forms.ColumnHeader VirtualMemory;
    private System.Windows.Forms.ColumnHeader Priority;
    private System.Windows.Forms.ColumnHeader Id;
    private System.Windows.Forms.Label machinename;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.ListBox listBox1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.ListView listView1;
    private System.Windows.Forms.ColumnHeader ThreadID;
    private System.Windows.Forms.ColumnHeader ThreadPriority;
    private System.Windows.Forms.ColumnHeader ProcessorTime;
    private ArrayList sProcIds;
    public Form1() {
        this.label1 = new System.Windows.Forms.Label();
        this.label2 = new System.Windows.Forms.Label();
        this.label3 = new System.Windows.Forms.Label();
        this.machinename = new System.Windows.Forms.Label();
        this.ThreadPriority = new System.Windows.Forms.ColumnHeader();
        this.ThreadID = new System.Windows.Forms.ColumnHeader();
        this.VirtualMemory = new System.Windows.Forms.ColumnHeader();
        this.listBox1 = new System.Windows.Forms.ListBox();
        this.listView1 = new System.Windows.Forms.ListView();
        this.ProcessorTime = new System.Windows.Forms.ColumnHeader();
        this.Priority = new System.Windows.Forms.ColumnHeader();
        this.Id = new System.Windows.Forms.ColumnHeader();
        this.button1 = new System.Windows.Forms.Button();
        this.SuspendLayout();
        this.label1.Location = new System.Drawing.Point(16, 16);
        this.label1.Size = new System.Drawing.Size(88, 16);
        this.label1.Text = "Machine name:";
        this.label2.Location = new System.Drawing.Point(16, 48);
        this.label2.Size = new System.Drawing.Size(100, 16);
        this.label2.Text = "Running Processes:";
        this.label3.Location = new System.Drawing.Point(16, 184);
        this.label3.Size = new System.Drawing.Size(100, 16);
        this.label3.Text = "Threads:";
        this.machinename.Location = new System.Drawing.Point(128, 16);
        this.machinename.Size = new System.Drawing.Size(100, 16);
        this.ThreadPriority.Text = "Priority";
        this.ThreadID.Text = "Thread ID";
        this.VirtualMemory.Text = "Virtual Mem";
        this.listBox1.Location = new System.Drawing.Point(16, 80);
        this.listBox1.Size = new System.Drawing.Size(408, 95);
        this.listBox1.SelectedIndexChanged += new
           System.EventHandler(this.SelectItemHandler);
        this.listView1.Columns.AddRange(new
           System.Windows.Forms.ColumnHeader[] {
          this.ThreadID,
          this.ThreadPriority,
          this.ProcessorTime});
        this.listView1.Location = new System.Drawing.Point(16, 200);
        this.listView1.Size = new System.Drawing.Size(408, 97);
        this.ProcessorTime.Text = "Processor Time";
        this.ProcessorTime.Width = 90;
        this.Priority.Text = "Priority";
        this.Id.Text = "ID";
        this.Id.Width = 20;
        this.button1.Location = new System.Drawing.Point(352, 312);
        this.button1.Size = new System.Drawing.Size(64, 24);
        this.button1.Text = "Close";
        this.button1.Click += new
             System.EventHandler(this.button1_Click);
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(440, 349);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
                     this.listView1,
                     this.machinename,
                     this.button1,
                     this.label3,
                     this.listBox1,
                     this.label2,
                     this.label1});
        this.ResumeLayout(false);
        sProcIds = new ArrayList();
        machinename.Text = Process.GetCurrentProcess().MachineName;
        Process[] sProcess = Process.GetProcesses();
        foreach (Process p in sProcess) {
            listBox1.Items.Add(p.ProcessName);
            sProcIds.Add(p.Id);
        }
    }
    protected void SelectItemHandler(object sender, System.EventArgs e) {
        int idx = this.listBox1.SelectedIndex;
        Process proc = Process.GetProcessById((int)sProcIds[idx]);
        ProcessThreadCollection procThreads = proc.Threads;
        this.listView1.View = System.Windows.Forms.View.Details;
        this.listView1.Items.Clear();
        int nRow = 0;
        foreach (ProcessThread pt in procThreads) {
            string priority = "Normal";
            switch ((int)proc.BasePriority) {
                case 8:
                    priority = "Normal";
                    break;
                case 13:
                    priority = "High";
                    break;
                case 24:
                    priority = "Real Time";
                    break;
                case 4:
                default:
                    priority = "Idle";
                    break;
            }
            this.listView1.Items.Add(pt.Id.ToString());
            this.listView1.Items[nRow].SubItems.Add(priority);
            this.listView1.Items[nRow].SubItems.Add(pt.UserProcessorTime.ToString());
            nRow++;
        }
    }
    protected void button1_Click(object sender, System.EventArgs e) {
        Close();
    }
    public static void Main(string[] args) {
        Application.Run(new Form1());
    }
}


List Process

using System;
using System.Diagnostics;
public class ListProcs
{
   public static void Main()
   {
      int totMemory = 0;
      Console.WriteLine("Info for all processes:");
      Process[] allProcs = Process.GetProcesses();
      foreach(Process thisProc in allProcs)
      {
         string procName = thisProc.ProcessName;
         DateTime started = thisProc.StartTime;
         int procID = thisProc.Id;
         int memory = thisProc.VirtualMemorySize;
         int priMemory = thisProc.PrivateMemorySize;
         int physMemory = thisProc.WorkingSet;
         totMemory += physMemory;
         int priority = thisProc.BasePriority;
         TimeSpan cpuTime = thisProc.TotalProcessorTime;
         Console.WriteLine("Process: {0}, ID: {1}", procName, procID);
         Console.WriteLine("    started: {0}", started.ToString());
         Console.WriteLine("    CPU time: {0}", cpuTime.ToString());
         Console.WriteLine("    virtual memory: {0}", memory);
         Console.WriteLine("    private memory: {0}", priMemory);
         Console.WriteLine("    physical memory: {0}", physMemory);
      }
      Console.WriteLine("\nTotal physical memory used: {0}", totMemory);
   }
}


List Threads

using System;
using System.Diagnostics;
public class ListThreads
{
   public static void Main()
   {
      Process[] allProcs = Process.GetProcesses();
      foreach(Process proc in allProcs)
      {
         ProcessThreadCollection myThreads = proc.Threads;
         Console.WriteLine("process: {0},  id: {1}", proc.ProcessName, proc.Id);
         foreach(ProcessThread pt in myThreads)
         {
            DateTime startTime = pt.StartTime;
            TimeSpan cpuTime = pt.TotalProcessorTime;
            int priority = pt.BasePriority;
            ThreadState ts = pt.ThreadState;
            Console.WriteLine("  thread:  {0}", pt.Id);
            Console.WriteLine("    started: {0}", startTime.ToString());
            Console.WriteLine("    CPU time: {0}", cpuTime);
            Console.WriteLine("    priority: {0}", priority);
            Console.WriteLine("    thread state: {0}", ts.ToString()); 
         }
      }
   }
}


Redirecting Process Output

using System;
using System.Diagnostics;
public class RedirectingProcessOutput
{
    public static void Main()
    {
        Process p = new Process();
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = "/c dir *.cs";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.Start();
        
        string output = p.StandardOutput.ReadToEnd();
        
        Console.WriteLine("Output:");
        Console.WriteLine(output);    
    }
}


Running another program from your own.

 

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;

public class MainClass {
    public static void Main() {
        Process.Start("notepad.exe", "");
        Process.Start("sol.exe", "");
    }
}


Start And Kill Process

 
using System;
using System.Diagnostics;
class MyProcessManipulator {
    static void Main(string[] args) {
        Process ieProc = Process.Start("IExplore.exe", "www.intertechtraining.ru");
        Console.Write("--> Hit a key to kill {0}...", ieProc.ProcessName);
        try {
            ieProc.Kill();
        } catch { } // In case user already killed it...
    }
}