Capture console exit C#

前端 未结 10 2017
悲&欢浪女
悲&欢浪女 2020-11-22 04:01

I have a console application that contains quite a lot of threads. There are threads that monitor certain conditions and terminate the program if they are true. This termi

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 04:57

    The link mentioned above by Charle B in comment to flq

    Deep down says:

    SetConsoleCtrlHandler won't work on windows7 if you link to user32

    Some where else in the thread it is suggested to crate a hidden window. So I create a winform and in onload I attached to console and execute original Main. And then SetConsoleCtrlHandle works fine (SetConsoleCtrlHandle is called as suggested by flq)

    public partial class App3DummyForm : Form
    {
        private readonly string[] _args;
    
        public App3DummyForm(string[] args)
        {
            _args = args;
            InitializeComponent();
        }
    
        private void App3DummyForm_Load(object sender, EventArgs e)
        {
            AllocConsole();
            App3.Program.OriginalMain(_args);
        }
    
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool AllocConsole();
    }
    

提交回复
热议问题