C#进程操作

C#进程操作

转:http://www.cnblogs.com/vienna/p/3560804.html

一、C#关闭word进程 
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("WINWORD"))
{
    p.Kill();
}

 

网上的2种方法:http://www.cnblogs.com/oneisyou/archive/2010/05/20/1739991.html

1)GC.Collect() ——不一定有效(我这里一定不有效);

2)孟宪会的Kill方法——会关掉所有Excel进程。

研究改进了一下Kill方法,如下:

foreach (Process p in Process.GetProcessesByName("Excel"))
{
    if (string.IsNullOrEmpty(p.MainWindowTitle))
    {
        p.Kill();
    }
}

 

二、C#进程管理启动和停止

 

C#进程的开始和结束,源码如下,谢谢

转载请注明出处http://www.cnblogs.com/aaaaa/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
//引用命名空间
using System.Diagnostics;
using System.Threading;


namespace StartStopProcess
{
    public partial class Form1 : Form
    {
        int fileIndex;
        string fileName = "Notepad.exe";
        Process process1 = new Process();
        public Form1()
        {
            InitializeComponent();
            //以详细列表方式显示
            listView1.View = View.Details;
            //参数含义:列名称,宽度(像素),水平对齐方式
            listView1.Columns.Add("进程ID", 70, HorizontalAlignment.Left);
            listView1.Columns.Add("进程名称", 70, HorizontalAlignment.Left);
            listView1.Columns.Add("占用内存", 70, HorizontalAlignment.Left);
            listView1.Columns.Add("启动时间", 70, HorizontalAlignment.Left);
            listView1.Columns.Add("文件名", 280, HorizontalAlignment.Left);
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            string argument = Application.StartupPath + "\\myfile" + fileIndex + ".txt";
            if (File.Exists(argument)==false)
            {
                File.CreateText(argument);
            }
            //设置要启动的应用程序名称及参数
            ProcessStartInfo ps = new ProcessStartInfo(fileName, argument);
            ps.WindowStyle = ProcessWindowStyle.Normal;
            fileIndex++;
            Process p = new Process();
            p.StartInfo = ps;
            p.Start();
            //等待启动完成,否则获取进程信息可能会失败
            p.WaitForInputIdle();
            RefreshListView();
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            //创建新的Process组件的数组,并将它们与指定的进程名称(Notepad)的所有进程资源相关联.
            Process[] myprocesses;
            myprocesses = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(fileName));
            foreach (Process p in myprocesses)
            {
                //通过向进程主窗口发送关闭消息达到关闭进程的目的
                p.CloseMainWindow();
                //等待1000毫秒
                Thread.Sleep(1000);
                //释放与此组件关联的所有资源
                p.Close();
            }
            fileIndex = 0;
            RefreshListView();
            this.Cursor = Cursors.Default;
        }

        private void RefreshListView()
        {
            listView1.Items.Clear();
            //创建Process类型的数组,并将它们与系统内所有进程相关联
            Process[] processes;
            processes = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(fileName));
            foreach (Process p in processes)
            {
                //将每个进程的进程名称、占用的物理内存以及进程开始时间加入listView中
                ListViewItem item = new ListViewItem(
                    new string[]{
                        p.Id.ToString(),
                        p.ProcessName,
                        string.Format("{0} KB", p.PrivateMemorySize64/1024.0f),
                        string.Format("{0}",p.StartTime),
                        p.MainModule.FileName
                    });
                listView1.Items.Add(item);
            }
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            RefreshListView();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

 

 

三、C# 之进程操作

http://www.cnblogs.com/acis_/archive/2009/07/19/1526389.html

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

 

 四、c#操作excel后关闭excel.exe的方法

转:http://www.cnblogs.com/dyllove98/p/3177940.html

关闭进程

C#和Asp.net下excel进程一被打开,有时就无法关闭,   尤其是website.对关闭该进程有过GC、release等方法,但这些方法并不是在所有情况下均适用。  于是提出了kill   process的方法,   目前我见过的方法多是用进程创建时间筛选excel.exe进程,   然后kill 。     这样的方法是不精确的,   也是不安全的,   通过对网上一些关于Api运用文章的阅读,   我找到了更为直接精确找到这个process并kill的方法,以下就是代码        
using   System.Runtime.InteropServices;  
     
  [DllImport("User32.dll",   CharSet   =   CharSet.Auto)]  
  public   static   extern   int   GetWindowThreadProcessId(IntPtr   hwnd,   out   int   ID);  
  protected   void   Button1_Click(object   sender,   EventArgs   e)  
  {  
      Excel.ApplicationClass   excel   =   new   Microsoft.Office.Interop.Excel.ApplicationClass();  
      excel.Workbooks.Open("d:\aaa.xls",   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing);  
      IntPtr   t   =   new   IntPtr(excel.Hwnd);  
      int   k   =   0;  
      GetWindowThreadProcessId(t,   out   k);  
      System.Diagnostics.Process   p   =   System.Diagnostics.Process.GetProcessById(k);  
      p.Kill();                  
   }


以上代码百分百成功的关闭excel.exe进程
我的做法是结合两者,先释放资源,然后关闭进程。
同时网上说避免使用GC.Collect 方法 (),因为会导致整个clr进行gc,影响你的性能.所以我也没有调用GC.Collect

posted @ 2014-08-26 17:21  flylong0204  阅读(1129)  评论(0编辑  收藏  举报