Simply grasp the method of starting external program process by C in Windows
- 2021-09-12 01:51:01
- OfStack
Many users need to use C # to start an external program (process) in the process of program development, and hope to close it after using the external program. Here, we give a brief introduction to the method of starting and shutting down external processes in C #.
There are two ways for C # to start external programs (processes): one is to directly use Process class provided by C #, and use the function operation of the class to directly start external programs; Another method is to use the traditional Win32 API function CreateProcess to start the external process.
Using the Process class provided by C # to start an external program method is relatively simple, and the example code is as follows:
using System.Diagnostics; // Includes Process Definition of class
int myprocessID; // Process ID
// Method 1 Direct use .Net Offered Process Class to start an external program
private void openButton_Click(object sender, EventArgs e)
{
Process myProcess = Process.Start('\\NandFlash\\SerialTST.exe', ''); // Start an external process
myprocessID = myProcess.Id; // Get the external process ID
}
Use the traditional Win32 API The method of the function is relatively complex, and the code is as follows:
using System.Runtime.InteropServices; // Use external Win32 API
#region Win32 API CreateProcess Function declaration makes a function declaration.
[DllImport('coredll.Dll', EntryPoint = 'CreateProcess', SetLastError = true)]
extern static int CreateProcess(string strImageName, string strCmdLine,
IntPtr pProcessAttributes, IntPtr pThreadAttributes,
int bInheritsHandle, int dwCreationFlags,
IntPtr pEnvironment, IntPtr pCurrentDir,
IntPtr bArray, ProcessInfo oProc);
public class ProcessInfo
{
public int hProcess;
public int hThread;
public int ProcessID;
public int ThreadID;
}
#endregion
Method 2: Use Win32 API to start an external program
private void openButton_Click(object sender, EventArgs e)
{
ProcessInfo pi = new ProcessInfo();
CreateProcess('\\NandFlash\\SerialTST.exe', '', IntPtr.Zero, IntPtr.Zero,
0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, pi);
myprocessID = pi.ProcessID; // Object for the program ID
}
The way to close an external process is directly through the obtained external process's ID To shut it down. Only the use of the .Net Adj. Process Method of class:
// Shut down an external process
private void closeButton_Click(object sender, EventArgs e)
{
Process myProcessA = Process.GetProcessById(myprocessID); // Pass ID Associated process
myProcessA.Kill(); // kill Process
}