using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management;
namespace 不允许外部调用
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Process proc = Process.GetCurrentProcess();
if (!FillDetailUseWmi(proc.Id).ToLower().Equals("explorer".ToLower()))
{
MessageBox.Show("该程序禁止外部程序调用。");
Application.ExitThread();
}
else
{
Application.Run(new Form1());
}
}
//// <summary>
/// 使用Wmi获取指定进程的创建者等信息
/// </summary>
/// <param name="pID">进程ID</param>
private static string FillDetailUseWmi(int pID)
{
string pname = string.Empty;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ProcessID=" + pID);
ManagementObjectCollection moc = searcher.Get();
ManagementOperationObserver observer = new ManagementOperationObserver();
HandleObjectReady hor = new HandleObjectReady();
//监测异步方法是否已成功返回
observer.ObjectReady += new ObjectReadyEventHandler(hor.Done);
foreach (ManagementObject mo in moc)
{
//异步调用该对象的GetOwner方法,获取进程创建者
mo.InvokeMethod(observer, "GetOwner", null);
//等待异步调用返回
while (!hor.Complete)
{
System.Threading.Thread.Sleep(500);
}
string user = "";
//判断获取用户名的操作是否成功
if (hor.Obj["returnValue"].ToString() == "0")
{
user = hor.Obj.Properties["User"].Value.ToString();
}
if (mo["ParentProcessID"] != null )
{
//根据父进程ID获取父进程名称
int vpID=Convert.ToInt32(mo["ParentProcessID"]);
pname = Process.GetProcessById(vpID).ProcessName;
}
}
//释放资源
searcher.Dispose();
searcher = null;
moc.Dispose();
moc = null;
observer = null;
hor = null;
return pname;
}
/**/
/// <summary>
/// 该类用于监测Wmi异步调用方法是否已经返回
/// </summary>
public class HandleObjectReady
{
private bool complete = false;
private ManagementBaseObject obj;
public void Done(object sender, ObjectReadyEventArgs e)
{
complete = true;
obj = e.NewObject;
}
public bool Complete
{
get
{
return complete;
}
}
public ManagementBaseObject Obj
{
get
{
return obj;
}
}
}
}
}
|