c# - 在控制台关闭时运行代码?

标签 c# .net-4.0 sharpdevelop

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

我该怎么做?

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

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

请仅在解决方案在通过 X 按钮关闭控制台和计算机关闭(通常通过 Windows,我知道如果电源被拔掉 xD)时都运行的情况下运行时回答。

最佳答案

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

它完全可以满足您的需求。

问候,

关于c# - 在控制台关闭时运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9897247/

相关文章:

c# - 您是否建议使用SharpDevelop在Linux上试用C#?

c# - C# 中的简单 LINQ 问题

c# - 哪种算法更适合加密和解密项目内的数据?

c# - SellectCommad.connection 属性未初始化

data-structures - 存储需要在.Net中大量查找的整数列表的最有效数据结构是什么?

c# - 应用程序将我的本地路径抛出为客户端计算机上的错误

c# - 创建相册查看器

c# - Linq 读取缺少节点的 XML 文档

c# - 如何创建一个支持转换为 sql 的方法?