在控制台关闭运行代码?

时间:2012-03-27 20:32:23

标签: c# .net-4.0 sharpdevelop

我正在编写一个C#应用程序,需要在控制台关闭时上传文件(无论是通过X按钮,还是关闭计算机)。

我怎么能这样做?

AppDomain.CurrentDomain.ProcessExit += new EventHandler (OnExit);

仅在我向控制台发出exit命令时运行,而不是在我按下红色关闭按钮时运行。

请仅在解决方案通过X按钮关闭控制台时运行解决方案,并且当计算机关闭时(通常通过Windows,我知道如果电源被拉到xD则不能),请回答。

3 个答案:

答案 0 :(得分:10)

您必须调用WIN32 API才能执行此操作,请在此处查看此帖子 http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/707e9ae1-a53f-4918-8ac4-62a1eddb3c4a/

我从那里复制了相关代码:

class Program

{
    private static bool isclosing = false;

    static void Main(string[] args)
    {
        SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);

        Console.WriteLine("CTRL+C,CTRL+BREAK or suppress the application to exit");

        while (!isclosing) ;
    }

    private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
    {
        // Put your own handler here

        switch (ctrlType)
        {
            case CtrlTypes.CTRL_CLOSE_EVENT:
                isclosing = true;
                Console.WriteLine("Program being closed!");
                break;
        }

        return true;
    }

    #region unmanaged
    // Declare the SetConsoleCtrlHandler function
    // as external and receiving a delegate.

    [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
    }

    #endregion
}

它完全符合您的需要。

问候,

答案 1 :(得分:1)

我还建议您保存要上传的内容,以便以后上传不会丢失/无效的文件。这样,下次启动应用程序时,可以执行上载。这个至少适用于系统注销/关机:

SystemEvents.SessionEnding += (SystemEvents_SessionEnding);

private static void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
    //code to run on when user is about to logoff or shutdown
}

答案 2 :(得分:0)

可能是这样的事情(假设我理解你的要求)

//get all command windows in the system
Process[] processes = Process.GetProcessesByName("cmd");


// find that one you interested in 
Process mypro;

订阅Process.Exited事件,如

mypro.Exited += (s,e) =>
{
   //here upload the file
}

应该为你工作。