views:

262

answers:

1

Hello everyone. I have a Windows Form that starts some console application in background(CreateNoWindow = rue,WindowStyle = ProcessWindowStyle.Hidden).

Windows form gives me opportunity to stop the console application at any time. But I'd like to handle somehow the close message inside the console application. I tried to use hooking like:

    [DllImport("Kernel32")]
    public static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, bool add);

    // A delegate type to be used as the handler routine 
    // for SetConsoleCtrlHandler.
    public delegate bool HandlerRoutine(CtrlTypes ctrlType);

    // An enumerated type for the control messages
    // sent to the handler routine.
    public enum CtrlTypes
    {
        CTRL_C_EVENT = 0,
        CTRL_BREAK_EVENT,
        CTRL_CLOSE_EVENT,
        CTRL_LOGOFF_EVENT = 5,
        CTRL_SHUTDOWN_EVENT
    }

    private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
    {
        StaticLogger.Instance.DebugFormat("Main: ConsoleCtrlCheck: Got event {0}.", ctrlType);
        if (ctrlType == CtrlTypes.CTRL_CLOSE_EVENT)
        {
            // Handle close stuff
        }
        return true;
    }

    static int Main(string[] args)
    {
        // Subscribing
        HandlerRoutine hr = new HandlerRoutine(ConsoleCtrlCheck);
        SetConsoleCtrlHandler(hr, true);
        // Doing stuff
    }

but I get the message inside ConsoleCtrlCheck only if the console window is created. But if window is hidden - I don't get any message.

In my windows Form to close console application process I use proc.CloseMainWindow(); to send message to the console window.

P.S. AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; - also does not help

Do you now other way to handle this situation? Thanks.

A: 

As you are starting a separate process for your console application, you could hook the Process.Exited event, which will be raised when the console application process shuts down.

ProcessStartInfo info = new ProcessStartInfo();
//set up info

Process process = new Process();
process.EnableRaisingEvents = true;
process.StartInfo = info;
process.Exited += delegate { /* DO some stuff when the process exist... */};
process.Start();
chibacity
The only way to hook it (as I found over the net) is the same as I used: http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspxA lot of articles just duplicate this code and propose nothing else.And what you are proposing - is handling things in calling process, and I need to do job in called process from inside.
LexRema
Ah yes I see you need to handle it in the calling application.
chibacity