C#获取进程和对进程的操作
最近看到一个考试系统,有个功能是用来监视进程的。一旦发现如communicator.exe这样的违禁软件就立即杀死进程并上报给服务器。我稍 微研究了一下,这个功能实现起来其实很简单。就是使用managementobjectsearcher获取进程列表,然后放在一个collection 里,之后就可以按照自己的逻辑去做了。
using system;
using system.management;
namespace consoleapplication3
{
class program
{
static void main(string[] args)
{
// show process list
console.writeline("===========process list===========");
managementobjectcollection objects = new managementobjectsearcher("select * from win32_process").get();
foreach (managementobject item in objects)
{
console.writeline((item["name"].tostring()));
}
// create ban list
console.writeline("===========ban list===========");
string lst = "communicator.exe,powerpnt.exe,notepad.exe";
string[] bannedproc = lst.split(‘,‘);
foreach (string s in bannedproc)
{
console.writeline(s);
}
// search and destroy
console.writeline("===========search and destroy===========");
console.writeline("searching for banned process...");
int count = 0;
foreach (string item in bannedproc)
{
if (detectprocess(item))
{
count++;
console.writeline("process [{0}] detected!", item);
console.writeline("[{0}] was killed {1}.", item, killprocess(item) ? "successfully" : "unsucessfully");
}
}
console.writeline("done, {0} banned process found", count);
}
protected static bool detectprocess(string pprocessname)
{
managementobjectcollection objects = new managementobjectsearcher("select * from win32_process").get();
foreach (managementobject item in objects)
{
string str = item["name"].tostring();
if (str.trim().toupper() == pprocessname.trim().toupper())
{
return true;
}
}
return false;
}
public static bool killprocess(string pprocessname)
{
managementobjectcollection objects = new managementobjectsearcher("select * from win32_process").get();
foreach (managementobject item in objects)
{
string str = item["name"].tostring();
if (str.trim().toupper() == pprocessname.trim().toupper())
{
string[] args = new string[] { "0" };
item.invokemethod("terminate", args);
return true;
}
}
return false;
}
}
}
效果如下: