2 回答

TA貢獻2041條經(jīng)驗 獲得超4個贊

TA貢獻1805條經(jīng)驗 獲得超10個贊
另一個解決方案(很容易理解)是使用一個幫助程序,如果你的進程存在,我在我的很多程序中使用這個解決方案來監(jiān)督(我不是這個想法的作者,不記得我在哪里找到這個想法,我剛剛修改了代碼):您可以刪除退出事件中的臨時文件..
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.");
}
}
必須有更好的方法來檢查殺戮,可能是在任務(wù)管理器上捕獲消息,或者掛鉤到任務(wù)管理器。但是,解決方案變得更加復雜
- 2 回答
- 0 關(guān)注
- 353 瀏覽
添加回答
舉報