1、创建进程
using System;
using System.Diagnostics;
using System.ComponentModel;
namespace MyProcessSample
{
class MyProcess
{
public static void Main()
{
try
{
using (Process myProcess = new Process())
{
myProcess.StartInfo.UseShellExecute = false;
// You can start any process, HelloWorld is a do-nothing example.
myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
// This code assumes the process you are starting will terminate itself.
// Given that is is started without a window so you cannot terminate it
// on the desktop, it must terminate itself or you can do it programmatically
// from this application using the Kill method.
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
Process instance = null;
Process[] arr = Process.GetProcessesByName("DataMaster"); //获取原先已运行的进程
if (arr.Length > 0)
{
instance = arr[0];
ShowWindowAsync(intPtr, SW_SHOWNORMAL); //已有运行的进程,显示其主窗体
}
else
{
instance = new Process();
instance.StartInfo.UseShellExecute = false;
string strExe = System.Environment.CurrentDirectory + @"\DataMaster.exe";
instance.StartInfo.FileName = strExe;
instance.StartInfo.CreateNoWindow = false;
instance.Start();
}
2、关闭进程
方案一
/// <summary>
/// 运行DOS命令
/// DOS关闭进程命令(ntsd -c q -p PID )PID为进程的ID
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public static string RunCmd(string command)
{
//實例一個Process類,啟動一個獨立進程
System.Diagnostics.Process p = new System.Diagnostics.Process();
//Process類有一個StartInfo屬性,這個是ProcessStartInfo類,包括了一些屬性和方法,下面我們用到了他的幾個屬性:
p.StartInfo.FileName = "cmd.exe"; //設定程序名
p.StartInfo.Arguments = "/c " + command; //設定程式執行參數
p.StartInfo.UseShellExecute = false; //關閉Shell的使用
p.StartInfo.RedirectStandardInput = true; //重定向標準輸入
p.StartInfo.RedirectStandardOutput = true; //重定向標準輸出
p.StartInfo.RedirectStandardError = true; //重定向錯誤輸出
p.StartInfo.CreateNoWindow = true; //設置不顯示窗口
p.Start(); //啟動
//p.StandardInput.WriteLine(command); //也可以用這種方式輸入要執行的命令
//p.StandardInput.WriteLine("exit"); //不過要記得加上Exit要不然下一行程式執行的時候會當機
return p.StandardOutput.ReadToEnd(); //從輸出流取得命令執行結果
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
System.Windows.Application.Current.Shutdown();
string exeName = Process.GetCurrentProcess().MainModule.FileName;
string[] exeArray = exeName.Split('\\');
RunCmd("taskkill /im " + exeArray[exeArray.Length-1] + " /f ");
}
方案二
/// <summary>
/// 关闭进程
/// </summary>
/// <param name="processName">进程名</param>
///通过进程名获取进程时,需要去掉扩展名exe,比如“QQ”
private void KillProcess(string processName)
{
Process[] myproc = Process.GetProcesses();
foreach (Process item in myproc)
{
if (item.ProcessName == processName)
{
item.Kill();
item.WaitForExit(); // possibly with a timeout
}
}
}
参考:
https://www.cnblogs.com/babycool/p/3570648.html
https://docs.microsoft.com/zh-cn/dotnet/api/system.diagnostics.process?view=netcore-3.1