| The code is as follows: |
Copy code |
Using System; Using System. Collections. Generic; Using System. Linq; Using System. Windows. Forms; Using System. Diagnostics; Using System. Management; External calls are not allowed for namespace { Static class Program { /// <Summary> /// Main entry point of the application. /// </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 ("This program prohibits external program calls. "); Application. ExitThread (); } Else { Application. Run (new Form1 ()); } } //// <Summary> /// Use Wmi to obtain information such as the creator of a specified process /// </Summary> /// <Param name = "pID"> process 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 (); // Monitor whether the asynchronous method has been returned successfully Observer. ObjectReady + = new ObjectReadyEventHandler (hor. Done ); Foreach (ManagementObject mo in moc) { // Call the GetOwner method of the object asynchronously to obtain the process creator. Mo. InvokeMethod (observer, "GetOwner", null ); // Wait for the Asynchronous call to return While (! Hor. Complete) { System. Threading. Thread. Sleep (500 ); } String user = ""; // Determine whether the operation for obtaining the user name is successful If (hor. Obj ["returnValue"]. ToString () = "0 ") { User = hor. Obj. Properties ["User"]. Value. ToString (); } If (mo ["ParentProcessID"]! = Null) { // Obtain the parent process name based on the parent process ID Int vpID = Convert. ToInt32 (mo ["ParentProcessID"]); Pname = Process. Getprocpolicyid (vpID). ProcessName; } } // Release resources Searcher. Dispose (); Searcher = null; Moc. Dispose (); Moc = null; Observer = null; Hor = null; Return pname; } /**/ /// <Summary> /// This class is used to monitor whether the Asynchronous call method of Wmi has been returned /// </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; } } } } } |
You need to add. Net reference System. Management