使用WMI控制Windows进程

本文主要介绍两种WMI的进行操作:检查进程是否存在、创建新进行

代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
using System.Threading;

namespace TJVictor.WMI
{
public class Win32_Process:WMIBaseClass
{
#region Property
private int timeout = 30;
public int TimeOut
{
get { return timeout; }
set { timeout = value; }
}

private string wqlSelect = "select * FROM Win32_Process where Name='{0}'";
#endregion

#region Construction
public Win32_Process()
: base()
{
base.Connection();
}

public Win32_Process(string domain, string Ip, string user, string psd)
: base(domain, Ip, user, psd)
{
base.Connection();
}
#endregion

#region public function
public bool IsProcessExist(string name)
{
if (!GetSelectQueryCollection(wqlSelect,name).Count.Equals(0))
return true;
return false;
}

public void CreateProcess(string name)
{
ManagementClass processClass = new ManagementClass("Win32_Process");
processClass.Scope = base.Scope;

ManagementBaseObject mbo = processClass.GetMethodParameters("Create");
mbo["CommandLine"] = string.Format(name);
ManagementBaseObject result = processClass.InvokeMethod("Create", mbo, null);
//检测执行结果
CheckExceptionClass.CheckProcessException(int.Parse(result["returnValue"].ToString()));
//检测进程是否执行完成
int tempTimeout = this.timeout;
while (!GetSelectQueryCollection("select * FROM Win32_Process where ProcessID='{0}'",result["ProcessID"].ToString()).Count.Equals(0))
{
if (tempTimeout.Equals(0))
{
throw new TJVictor.WMI.WmiException.ProcessException(
string.Format("在 {0} 上执行 {1} 操作失败,执行超时", base.Ip, name));
}
tempTimeout--;
Thread.Sleep(1000);
}
}
#endregion
}
}

<!-- .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } -->

如需转载,请注明本文原创自优快云 TJVictor专栏:http://blog.youkuaiyun.com/tjvictor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值