14

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

我怎么能这样做?

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

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

请仅在通过 X 按钮关闭控制台和关闭计算机时(通常通过 Windows,我知道如果断电 xD 时您不能)同时运行解决方案,请回答。

4

3 回答 3

14

您必须调用 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
}

它完全符合您的需要。

问候,

于 2012-03-27T20:39:53.537 回答
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
}
于 2012-03-27T20:49:21.157 回答
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
}

应该为你工作。

于 2012-03-27T20:38:12.443 回答