//判断程序是否在运行,如果未运行就启动该程序
Timer timer = new Timer();
protected override void OnStart(string[] args)
{
timer.Interval = 15 * 1000;
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
timer.AutoReset = true;
timer.Start();
}
public void OnTimedEvent(object sender, ElapsedEventArgs e)
{
const string fileName = @"D:projectpssYGPS.PSSPrintServiceinDebugPrintService.exe";
string programName = System.IO.Path.GetFileNameWithoutExtension(fileName);// fileName.Replace(ext, "");
var isAlive = IsProcessStarted(programName);
if (!isAlive)
{
//声明一个程序信息类
ProcessStartInfo procInfo = new ProcessStartInfo();
//设置外部程序名
procInfo.FileName = fileName;
//procInfo.WindowStyle = ProcessWindowStyle.Normal;
//设置外部程序的启动参数(命令行参数)
procInfo.Arguments = @"D:";
//procInfo.CreateNoWindow = true;
//设置外部程序工作目录为 C:
procInfo.WorkingDirectory = @"D:projectpssYGPS.PSSPrintServiceinDebug";
//设置启动动作,确保以管理员身份运行
procInfo.Verb = "runas";
//启动外部程序
//Process proc = Process.Start(procInfo);
Process.Start(procInfo);
}
}
/// <summary>
/// 此函数用于判断某一外部进程是否打开
/// </summary>
/// <param name="processName">参数为进程名</param>
/// <returns>如果打开了,就返回true,没打开,就返回false</returns>
private bool IsProcessStarted(string processName)
{
try
{
Process[] temp = Process.GetProcessesByName(processName);
if (temp.Length > 0)
{
return true;
}
else
{
return false;
}
}
catch (Exception)
{
return false;
}
}
private static string CmdPath = @"C:WindowsSystem32cmd.exe";
/// <summary>
/// 执行cmd命令
/// 多命令请使用批处理命令连接符:
/// <![CDATA[
/// &:同时执行两个命令
/// |:将上一个命令的输出,作为下一个命令的输入
/// &&:当&&前的命令成功时,才执行&&后的命令
/// ||:当||前的命令失败时,才执行||后的命令]]>
/// 其他请百度
/// </summary>
/// <param name="cmd"></param>
public static void RunCmd(string cmd,out string output )
{
cmd = cmd.Trim().TrimEnd('&') + "&exit";//说明:不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
using (Process p = new Process()) {
p.StartInfo.FileName = CmdPath; p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true; //重定向标准错误输出
p.StartInfo.CreateNoWindow = true; //不显示程序窗口
p.StartInfo.Verb = "runas"; p.Start();//启动程序
//向cmd窗口写入命令
p.StandardInput.WriteLine(cmd);
p.StandardInput.AutoFlush = true; ////获取cmd窗口的输出信息
//output = p.StandardOutput.ReadToEnd();
//p.WaitForExit();//等待程序执行完退出进程
//ReadtoEnd()容易卡住,使用ReadLine
//string tmptStr = proc.StandardOutput.ReadLine();
string outStr = "";
while (tmptStr != "")
{
outStr += tmptStr;
tmptStr = proc.StandardOutput.ReadLine();
}
p.Close();
}
}
#region 设置应用程序开机自动运行
string startup = Application.ExecutablePath;
//class Micosoft.Win32.RegistryKey. 表示Window注册表中项级节点,此类是注册表装
RegistryKey rKey = Registry.LocalMachine.OpenSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun", true);
if(rKey==null)
rKey= Registry.LocalMachine.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
rKey.SetValue("PrintService", startup);
rKey.Close();
#endregion
#region 开始启动菜单添加应用快捷方式
//获取当前系统用户启动目录
string startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
//获取当前系统用户桌面目录
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
FileInfo fileStartup = new FileInfo(startupPath + "\PrintService.lnk");
if (!fileStartup.Exists)
{
WshShell shell = new WshShell();
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(desktopPath + "\PrintService.lnk");
string exeDir = Application.StartupPath + "\PrintService.lnk";
//把程序快捷方式复制到启动目录
//System.IO.File.Copy(exeDir, startupPath + "\PrintService.lnk", true);
#endregion
//参考:http://www.cnblogs.com/weiwei858/p/6031026.html
查找进程、启用进程、关闭进程
using ……
using ……
using System.Diagnostics;
//启用进程
void process()
{
Process p;//实例化一个Process对象
p=Process.Start(@"E:1.txt");//要开启的进程(或 要启用的程序),括号内为绝对路径
p.Kill();//结束进程
}
//查找进程、结束进程
void killProcess()
{
Process[] pro = Process.GetProcesses();//获取已开启的所有进程
//遍历所有查找到的进程
for (int i = 0; i < pro.Length; i++)
{
//判断此进程是否是要查找的进程
if (pro[i].ProcessName.ToString().ToLower() == "pc_task")
{
pro[i].Kill();//结束进程
}
}
}
//启动、结束线程 http://www.cnblogs.com/zhangqs008/archive/2011/06/25/2341126.html
启动进程:
private void StartProcess()
{
try
{
if (!CheckProcessExists())
{
Process p = new Process();
p.StartInfo.FileName = System.IO.Path.Combine(Application.StartupPath, "DataTool.exe");
p.StartInfo.Arguments = "DataTool.exe";
p.StartInfo.UseShellExecute = true;
p.Start();
p.WaitForInputIdle(10000);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Source + " " + ex.Message);
}
}
private bool CheckProcessExists()
{
Process[] processes = Process.GetProcessesByName("DataTool");
foreach (Process p in processes)
{
if (System.IO.Path.Combine(Application.StartupPath, "DataTool.exe") == p.MainModule.FileName)
return true;
}
return false;
}
结束进程:
private void KillProcessExists()
{
Process[] processes = Process.GetProcessesByName("AppStart");
foreach (Process p in processes)
{
if (System.IO.Path.Combine(Application.StartupPath, "AppStart.exe") == p.MainModule.FileName)
{
p.Kill();
p.Close();
}
}
}
有时再写的客户端软件中,使用到比如Quartz.net 等定时作业调度组件时,
往往会出现自己的应用程序已经关闭了,但是进程还未结束,这时,需要在关闭窗口时的FormClosed事件里加上下面的代码:
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes)
{
if (process.Id == current.Id)
{
process.Kill();
}
}
}