2 回答
TA贡献2041条经验 获得超4个赞
TA贡献1805条经验 获得超10个赞
另一个解决方案(很容易理解)是使用一个帮助程序,如果你的进程存在,我在我的很多程序中使用这个解决方案来监督(我不是这个想法的作者,不记得我在哪里找到这个想法,我刚刚修改了代码):您可以删除退出事件中的临时文件..
static void Main(string[] args)
{
//Main App Process.
if (args.Length == 0)
{
//Saves current process info to pass on command line.
main = Process.GetCurrentProcess();
mainProcessID = main.Id;
//Initializes the helper process
checker = new Process();
checker.StartInfo.FileName = main.MainModule.FileName;
checker.StartInfo.Arguments = mainProcessID.ToString();
checker.EnableRaisingEvents = true;
checker.Exited += new EventHandler(checker_Exited);
//Launch the helper process.
checker.Start();
Application.Run(new MainForm()); // your winform app
}
else //On the helper Process
{
main = Process.GetProcessById(int.Parse(args[0]));
main.EnableRaisingEvents = true;
main.Exited += new EventHandler(main_Exited);
while (!main.HasExited)
{
Thread.Sleep(1000); //Wait 1 second.
}
//Provide some time to process the main_Exited event.
Thread.Sleep(2000);
}
}
//Double checks the user not closing the checker process.
static void checker_Exited(object sender, EventArgs e)
{
//This only checks for the task manager process running.
//It does not make sure that the app has been closed by it. But close enough.
//If you can think of a better way please let me know.
if (Process.GetProcessesByName("taskmgr").Length != 0)
{
MessageBox.Show("Task Manager killed helper process.");
//If you like you could kill the main app here to.
//main.Kill();
}
}
//Only gets to run on the checker process. The other one should be dead.
static void main_Exited(object sender, EventArgs e)
{
//This only checks for the task manager process running.
//It does not make sure that the app has been closed by it. But close enough.
//If you can think of a better way please let me know.
if (Process.GetProcessesByName("taskmgr").Length != 0)
{
MessageBox.Show("Task Manager killed my application.");
}
}
必须有更好的方法来检查杀戮,可能是在任务管理器上捕获消息,或者挂钩到任务管理器。但是,解决方案变得更加复杂
- 2 回答
- 0 关注
- 317 浏览
添加回答
举报