Edgar
Edgar

Reputation: 1120

how to run code on program process end

I'm using VS 2010, winForm.

Can someone suggest how to run method when program process is ended?

I tried: How to run code before program exit? solution, but it only works is I close form by "close button" if I end process in task-manager it is not called, is it possible to handle such event?

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
    AppDomain.CurrentDomain.ProcessExit += new EventHandler (OnProcessExit); 
}

public static void OnProcessExit(object sender, EventArgs e)
{
    if (Utils.RemindTime != DateTime.MinValue)
        Utils.SetStartup(true);
}

Upvotes: 0

Views: 2777

Answers (1)

TimothyP
TimothyP

Reputation: 21755

You use another program to start this program. Let's say your application is "notepad":

class Program
{
    static void Main(string[] args)
    {
        var startInfo = new ProcessStartInfo("notepad.exe");
        var process = Process.Start(startInfo);
        process.WaitForExit();
        //Do whatever you need to do here
        Console.Write("Notepad Closed");
        Console.ReadLine();
    }
}

You could to something similar with batch files on Windows or shell scripts in Linux.

Of course it doesn't give you access to the internals of the program you launched, but it's the only way you can make sure "some code" is executed after the process is killed by the task manager

Upvotes: 1

Related Questions