0

I try stop console application close but it closes before all functions is completed.. Example for stops to 90000 and then console get closed.. I want it first do all jobs end and then close console. Sorry my bad english.

Example:

    private delegate bool EventHandler(CtrlType sig);
    private enum CtrlType
    {
        CTRL_BREAK_EVENT = 1,
        CTRL_C_EVENT = 0,
        CTRL_CLOSE_EVENT = 2,
        CTRL_LOGOFF_EVENT = 5,
        CTRL_SHUTDOWN_EVENT = 6
    }
    private static EventHandler delegate0_0;
    [DllImport("Kernel32")]
    private static extern bool SetConsoleCtrlHandler(Program.EventHandler handler, bool add);
    private const int MF_BYCOMMAND = 0x00000000;
    public const int SC_CLOSE = 0xF060;

    static void Main(string[] args)
    {
        Program.delegate0_0 = (Program.EventHandler)Delegate.Combine(Program.delegate0_0, new Program.EventHandler(Program.smethod_1));
        Program.SetConsoleCtrlHandler(Program.delegate0_0, true);
        Console.ReadKey(true);
    }

    private static bool smethod_1(CtrlType enum0_0)
    {
        for (int i = 0; i < 10000000; i++)
        {
            Console.WriteLine(i);
        }

        return true;
    }
Tamir Vered
  • 9,690
  • 5
  • 42
  • 54
user3290224
  • 67
  • 1
  • 8
  • That's not possible. You've got 5 seconds to cleanup after you click the Close button, that's it. The sane way to go about it is not clicking the Close button until your program reports that it completed. – Hans Passant Feb 09 '14 at 17:53
  • Ok dam.. :( I try something else – user3290224 Feb 09 '14 at 18:13
  • @HansPassant Is possible if you click locked X button it can trigger? Example it says "PLEASE PRESS ESCAPE" – user3290224 Feb 09 '14 at 18:29

2 Answers2

1

use EventWaitHandle on your handle in order to wait for it to be signaled. you are using unmanaged handle so this is an equivalent API to WIN32's WaitForSingleObject(HANDLE h, DWORD duaration();

so this is the C# code:

EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);
handle.SafeWaitHandle = new Microsoft.Win32.SafeHandles.SafeWaitHandle(yourHandle,true);
handle.WaitOne();

the true in the SafeWaitHandle creation indicating that it should clean up along with the finalizer.

Tamir Vered
  • 9,690
  • 5
  • 42
  • 54
0

You can stop it by letting the programm await for user input at the end of your programm:

Console.ReadLine();

or

Console.ReadKey();

Original Thread: How to stop C# console applications from closing automatically?

Community
  • 1
  • 1
user1767754
  • 18,800
  • 14
  • 111
  • 133
  • If you dont see its there already AND you maybe didint read my question? – user3290224 Feb 09 '14 at 18:13
  • 1
    To be fair, @user3290224, your question is not at all clear, and is easily misunderstood. Care to go into more detail, expressing in words what your code is trying to do? – Michael Petrotta Feb 09 '14 at 18:16