C# 启动、关闭windows系统某个进程
private Dictionary<string, string> ServiceList = new Dictionary<string, string>();//服务文件对应服务名称
public void Init(){
ServiceList.Add("print", "SP");
ServiceList.Add("cashbox", "SC");
ServiceList.Add("display", "SD");
}
//开启某个服务进程
/// name为ServiceList中的key
private bool ExistService(string name)
{
try
{
if(ServiceList.Keys.Contains(name))
{
var service = ServiceList[name];
Process[] pros = Process.GetProcessesByName(service);
if(pros!=null && pros.Length)
{
}
else
{
Process proc = new Process();
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,$"{service}.exe");
proc.StartInfo.FileName = path;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
proc.StartInfo.UseShellExecute = false;
proc.Start();
string def="-1";
string flag = "";
string falgtime="";
switch(name)
{
case "print":
flag = IniHelper.Read("default","request",def,$"{name}".ini);
int.TryParse(flag,out printIndex);
flagtime = IniHelper.Read("default","time",def,$"{name}".ini);
long.TryParse(falgtime,out printTicks);
break;
}
}
return true;
}
}
catch(Exception ex)
{
logger.Error($"{ex.Message}---{ex.StackTrace}");
return false;
}
return false;
}
//关闭某个服务进程
public void CloseDevice()
{
foreach(var item in ServiceList)
{
Process[] process = Process.GetProcessesByName(item.Value);
if(process!=null && process.Length>0)
{
foreach(var pro in process)
{
pro.Kill();
}
}
}
}
IniHelper.cs
public static string Read(string section, string key, string def, string fileName)
{
var filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,fileName);
StringBuilder sb = new StringBuilder(1024);
GetPrivateProfileString(section,key,def,sb,1024,filepath);
return sb.ToString();
}
///<summary>
///为INI文件中指定的节点取得字符串
///</summary>
///<param name="lpAppName">欲在其中查找关键字的节点名称</param>
///<param name="lpKeyName">欲获取的项名</param>
///<param name="lpDefault">指定的项没有找到时返回的默认值</param>
///<param name="lpReturnendString">指定一个字符串缓冲区,长度至少为nSize</param>
///<param name="nSize">指定装载到lpReturnendString缓冲区的最大字符数量</param>
///<param name="lpFileName">INI文件完整路径</param>
///<returns>复制到lpReturnedString缓冲区的字节数量,其中不包括那些NULL中止字符</returns>
[DllImport("kernel32')]
private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnendString, int nSize, string lpFileName);
标签:ServiceList,string,C#,var,Process,window,某个,proc,name From: https://www.cnblogs.com/jnyyq/p/17555592.html