You need to add a reference to system. Management. dll.
CopyCode The Code is as follows: using system. diagnostics;
Using system. Management; static void main (string [] ARGs)
{
Foreach (PROCESS p in process. getprocesses ())
{
Console. Write (P. processname );
Console. Write ("----");
Console. writeline (getprocessusername (P. ID ));
}
Console. readkey ();
} Private Static string getprocessusername (int pid)
{
String text1 = NULL;
Selectquery query1 = new selectquery ("select * From win32_process where processid =" + PID );
Managementobjectsearcher searcher1 = new managementobjectsearcher (query1 );
Try
{
Foreach (managementobject disk in searcher1.get ())
{
Managementbaseobject inpar = NULL;
Managementbaseobject outpar = NULL;
Inpar = disk. getmethodparameters ("getowner ");
Outpar = disk. invokemethod ("getowner", inpar, null );
Text1 = outpar ["user"]. tostring ();
Break;
}
}
Catch
{
Text1 = "system ";
}
Return text1;
}