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

C#进程操作的更多相关文章

  1. Linux进程操作信息

    Linux进程操作简单小结 linux上进程有5种状态: 1. 运行(正在运行或在运行队列中等待) 2. 中断(休眠中, 受阻, 在等待某个条件的形成或接受到信号) 3. 不可中断(收到信号不唤醒和不 ...

  2. 在Python程序中的进程操作,multiprocess.Process模块

    在python程序中的进程操作 之前我们已经了解了很多进程相关的理论知识,了解进程是什么应该不再困难了,刚刚我们已经了解了,运行中的程序就是一个进程.所有的进程都是通过它的父进程来创建的.因此,运行起 ...

  3. python 全栈开发,Day38(在python程序中的进程操作,multiprocess.Process模块)

    昨日内容回顾 操作系统纸带打孔计算机批处理 —— 磁带 联机 脱机多道操作系统 —— 极大的提高了CPU的利用率 在计算机中 可以有超过一个进程 进程遇到IO的时候 切换给另外的进程使用CPU 数据隔 ...

  4. 基于ADB框架Robotium跨进程操作

    转自:http://blog.csdn.net/qingchunjun/article/details/42580937 2015年2月3日更新: 有些朋友在用真机尝试本方法时,抛出了InputStr ...

  5. 第十五章、python中的进程操作-开启多进程

    目录 第十五章.python中的进程操作-开启多进程 一.multprocess模块 二.multprocess.process模块 三.Process()对象方法介绍 四.Process()对象属性 ...

  6. Process Monitor监控进程操作注册表如何实现?

    http://zhidao.baidu.com/link?url=Kqav4qkQSprC5FnpHPOGJvhqvY9fJ9-Vdx9g_SWh4w5VOusdRJo4Vl7qIdrG4LwRJvr ...

  7. C# 调用word进程操作文档关闭进程

    C# 调用word进程操作文档关闭进程 作者:Jesai 时间:2018-02-12 20:36:23 前言: office办公软件作为现在主流的一款办公软件,在我们的日常生活和日常工作里面几乎每天都 ...

  8. Python程序中的进程操作--—--开启多进程

    Python程序中的进程操作-----开启多进程 之前我们已经了解了很多进程相关的理论知识,了解进程是什么应该不再困难了,刚刚我们已经了解了,运行中的程序就是一个进程.所有的进程都是通过它的父进程来创 ...

  9. 在python程序中的进程操作

    multiprocess模块 multiprocess不是一个模块而是python中一个操作.管理进程的包. 之所以叫multi是取自multiple的多功能的意思,在这个包中几乎包含了和进程有关的所 ...

随机推荐

  1. 攻城狮在路上(叁)Linux(十五)--- 文件与目录的默认权限与隐藏权限

    一.文件默认权限:umask <==需要被减去的权限. 1.umask指的是当前用户在新建文件或者目录时的默认权限,如0022; 2.默认情况下,用户创建文件的最大权限为666; 创建目录的最大 ...

  2. gnuplot安装问题(set terminal "unknown")

    今天在系统同上要装个gnuplot,原来用的都是拷好的虚拟机.这也是第一次装.本来以为分分钟的事,却不料遇到不少麻烦.记录一下,供大家参考 一,快速开始安装 ubuntu下那自然是: sudo apt ...

  3. 六款小巧的HTTP Server[C语言]

    1.micro_httpd - really small HTTP server特点: 支持安全的 .. 上级目录过滤 支持通用的MIME类型 支持简单的目录 支持目录列表 支持使用 index.ht ...

  4. sql2014 新建用户并登陆

    EXEC master.dbo.sp_addlogin @loginame = N'testuser1', @passwd = '123456', @defdb = N'master', @defla ...

  5. 【jQuery 区别】attr()和prop()的区别

    1>>> 今天实现一个 点击更新按钮 ,可以勾选上本行的的checkbox的功能: 使用代码: /** * updateproduct.htmls 更新 产品信息 */ $(docu ...

  6. Liferay 6.2 改造系列之十六:关闭OpenID模式的单点登录

    在/portal-master/portal-impl/src/portal.properties文件中,有如下配置: # # Set this to true to enable OpenId au ...

  7. DOM系列---基础篇

    DOM系列---基础篇   DOM (Document Object Model) 即文档对象模型, 针对 HTML 和 XML 文档的 API (应用程序接口) .DOM 描绘了一个层次化的节点树, ...

  8. Hibernate,一对一外键单向 记录。Timestamp 的一个坑。

    首先是2张表 表A: 表B: 其中表B中的FormBaseId对应表A中的SubjectID. 数据库中没有设置外键关系. 下面是2个对应的实体 package questionnaire.model ...

  9. CentOS7安装docker出错(Transaction check error)

    1. 出错内容: Transaction check error: :-.el7_2..x86_64 conflicts with :-.el7.x86_64 :-.el7_2..x86_64 con ...

  10. Sqlserver自定义函数Function

    一.FUNCTION: 在sqlserver2008中有3中自定义函数:标量函数/内联表值函数/多语句表值函数,首先总结下他们语法的异同点: 同点:1.创建定义是一样的:                ...