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#进程的开始和结束,源码如下,谢谢
转载请注明出处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();
}
}
转: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#进程操作的更多相关文章
- Linux进程操作信息
Linux进程操作简单小结 linux上进程有5种状态: 1. 运行(正在运行或在运行队列中等待) 2. 中断(休眠中, 受阻, 在等待某个条件的形成或接受到信号) 3. 不可中断(收到信号不唤醒和不 ...
- 在Python程序中的进程操作,multiprocess.Process模块
在python程序中的进程操作 之前我们已经了解了很多进程相关的理论知识,了解进程是什么应该不再困难了,刚刚我们已经了解了,运行中的程序就是一个进程.所有的进程都是通过它的父进程来创建的.因此,运行起 ...
- python 全栈开发,Day38(在python程序中的进程操作,multiprocess.Process模块)
昨日内容回顾 操作系统纸带打孔计算机批处理 —— 磁带 联机 脱机多道操作系统 —— 极大的提高了CPU的利用率 在计算机中 可以有超过一个进程 进程遇到IO的时候 切换给另外的进程使用CPU 数据隔 ...
- 基于ADB框架Robotium跨进程操作
转自:http://blog.csdn.net/qingchunjun/article/details/42580937 2015年2月3日更新: 有些朋友在用真机尝试本方法时,抛出了InputStr ...
- 第十五章、python中的进程操作-开启多进程
目录 第十五章.python中的进程操作-开启多进程 一.multprocess模块 二.multprocess.process模块 三.Process()对象方法介绍 四.Process()对象属性 ...
- Process Monitor监控进程操作注册表如何实现?
http://zhidao.baidu.com/link?url=Kqav4qkQSprC5FnpHPOGJvhqvY9fJ9-Vdx9g_SWh4w5VOusdRJo4Vl7qIdrG4LwRJvr ...
- C# 调用word进程操作文档关闭进程
C# 调用word进程操作文档关闭进程 作者:Jesai 时间:2018-02-12 20:36:23 前言: office办公软件作为现在主流的一款办公软件,在我们的日常生活和日常工作里面几乎每天都 ...
- Python程序中的进程操作--—--开启多进程
Python程序中的进程操作-----开启多进程 之前我们已经了解了很多进程相关的理论知识,了解进程是什么应该不再困难了,刚刚我们已经了解了,运行中的程序就是一个进程.所有的进程都是通过它的父进程来创 ...
- 在python程序中的进程操作
multiprocess模块 multiprocess不是一个模块而是python中一个操作.管理进程的包. 之所以叫multi是取自multiple的多功能的意思,在这个包中几乎包含了和进程有关的所 ...
随机推荐
- 跟着鸟哥学Linux系列笔记0-如何解决问题
跟着鸟哥学Linux系列笔记0-扫盲之概念 在发生问题怎么处理: 1. 在自己的主机.网络数据库上查询How-To或FAQ -Linux 自身的文件数据: /usr/share/doc -CLDP中 ...
- linux c学习笔记----互斥锁属性
转自:http://lobert.iteye.com/blog/1762844 互斥锁属性 使用互斥锁(互斥)可以使线程按顺序执行.通常,互斥锁通过确保一次只有一个线程执行代码的临界段来同步多个线程. ...
- C++读取txt文件
1. 逐行读入 void readTxt(string file) { ifstream infile; infile.open(file.data()); //将文件流对象与文件连接起来 asser ...
- Win7系统怎么开启远程桌面?Win7远程桌面怎么用(转)
远程桌面服务开启之后,可以方便的远程管理服务器或计算机.为生活和工作带来不少便利呢,很多小伙伴还不知道怎么开启win7远程桌面吧(下面咗嚛以内网远程桌面为例) 工具/原料 Win7 Win7远程桌 ...
- c++ 左值 和 右值
什么是lvalue, 什么是rvalue? lvalue: 具有存储性质的对象,即lvalue对象,是指要实际占用内存空间.有内存地址的那些实体对象,例如:变量(variables).函数.函数指针等 ...
- Redis在Windows下的安装和使用
NoSQL简介 介绍redis前,我想还是先认识下NoSQL,即not only sql, 是一种非关系型的数据存储,key/value键值对存储.现有Nosql DB 产品: Redis/Mongo ...
- hibernate常用配置
核心配置 核心配置有两种方式进行配置 1:属性文件的配置:hibernate.properties 格式:key=value hibernate.connection.driver_class=com ...
- 安卓图表引擎AChartEngine(三) - 示例源码折线图、饼图和柱状图
折线图: package org.achartengine.chartdemo.demo.chart; import java.util.ArrayList; import java.util.Lis ...
- transform(变形)和transform-origin(变形原点)
转载请说明出处,原文地址http://blog.sina.com.cn/s/blog_780a942701014xl8.html transform(变形)和transform-origin(变形原点 ...
- 2016.5.27 php测试中敏感度高,怎么调整
在测试PHP代码的过程中,会遇到这样的问题:PHP提示Notice: Undefined variable,遇到这样的问题很纠结,但是很容易解决. 今天晚上,我就遇到了这样的问题,到网上搜索了很多解决 ...