Parse the Process class in C # To kill the Process and execute in-depth analysis of commands

Source: Internet
Author: User

C # process-related sorting
1. Obtain the user name of a process based on the process name?
You need to add a reference to System. Management. dll. Copy codeThe 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;
}

The process name is p. ProcessName.
2. Process Retrieval
Using System. Diagnostics;
[Note] the System. Diagnostics namespace provides specific classes that allow you to interact with System processes, event logs, and performance counters.Copy codeThe Code is as follows: string str = "";
Process [] processes;
// Get the list of current active processes.
Processes = System. Diagnostics. Process. GetProcesses ();
// Grab some basic information for each process.
Process process;
For (int I = 0; I <processes. Length-1; I ++)
{
Process = processes [I];
Str = str + Convert. ToString (process. Id) + ":" +
Process. ProcessName + "\ r \ n ";
}
System. Windows. Forms. MessageBox. Show (str );
TxtProcessID. Text = processes [0]. Id. ToString ();
// Display process information
String s = "";
System. Int32 processid;
Process process;
Processid = Int32.Parse (txtProcessID. Text );
Process = System. Diagnostics. Process. GetProcessById (processid );
S = s + "overall priority category of the process:" + Convert. ToString (process. PriorityClass) + "\ r \ n ";
S = s + "Number of handles opened by this process:" + process. HandleCount + "\ r \ n ";
S = s + "Main Window title of the process:" + process. MainWindowTitle + "\ r \ n ";
S = s + "minimum working set size allowed by the process:" + process. MinWorkingSet. ToString () + "\ r \ n ";
S = s + "Maximum working set size allowed by the process:" + process. MaxWorkingSet. ToString () + "\ r \ n ";
S = s + "Paging memory size of the process:" + process. PagedMemorySize + "\ r \ n ";
S = s + "peak paging memory size of the process:" + process. PeakPagedMemorySize + "\ r \ n ";
System. Windows. Forms. MessageBox. Show (s );
}
Catch
{
System. Windows. Forms. MessageBox. Show ("invalid process ID! ");
}

[Note] the Int32 value type indicates a signed integer between-2,147,483,648 and + 2,147,483,647.
Int32 provides some methods to compare instances of this type, convert the Instance value to its String representation, and convert the String representation of numbers to instances of this type.
For information about how the format standard code controls the String representation of the value type, see format settings overview.
This type of implementation interfaces are IComparable, IFormattable, and IConvertible. Use the Convert class for conversion, instead of using this type of IConvertible explicit interface member.
It is worth mentioning that the Process class has many member variables, which can obtain almost every detail of the Process. In the above example, only a few Members are selected for demonstration. If necessary, you can refer to the MSDN Library to query the Process class members for more detailed information, which is not listed here.
3. Killing Processes
Copy codeThe Code is as follows: private void button2_Click (object sender, EventArgs e)
{
If (listView1.SelectedItems. Count> 0)
{
Try
{
String proName = listView1.SelectedItems [0]. Text;
Process [] p = Process. GetProcessesByName (proName );
P [0]. Kill ();
MessageBox. Show ("the process is disabled successfully! ");
GetProcess ();
}
Catch
{
MessageBox. Show ("unable to close this process! ");
}
}
Else
{
MessageBox. Show ("select the process to terminate! ");
}
}

Iv. Use the process class in C # To call external programs and execute doscommands
Copy codeThe Code is as follows: private string RunCmd (string command)
{
// A Process class of the instance to start an independent Process
Process p = new Process ();
// The Process class has a StartInfo attribute.
// Set the program name
P. StartInfo. FileName = "cmd.exe ";
// Set program execution Parameters
P. StartInfo. Arguments = "/c" + command;
// Close Shell usage
P. StartInfo. UseShellExecute = false;
// Redirect standard input
P. StartInfo. RedirectStandardInput = true;
P. StartInfo. RedirectStandardOutput = true;
// Redirect error output
P. StartInfo. RedirectStandardError = true;
// Set not to display the window
P. StartInfo. CreateNoWindow = true;
// Start
P. Start ();
// You can also enter the command to be executed in this way
// Remember to add Exit, or else the next line of code will run on the machine.
// P. StandardInput. WriteLine (command );
// P. StandardInput. WriteLine ("exit ");
// Obtain the command execution result from the output stream
Return p. StandardOutput. ReadToEnd ();
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.