【问题标题】:C# Windows Program Exit Request (Detect Application.Exit) No Forms [closed]C# Windows 程序退出请求(检测 Application.Exit)无表单 [关闭]
【发布时间】:2014-06-08 14:22:06
【问题描述】:

是否有可能在 Application.Exit 被调用后检测到,或者是否有一个 win32 函数可以知道 Windows 何时喜欢关闭您的程序,因为关闭或其他原因。没有表格。

【问题讨论】:

    标签: c# winapi


    【解决方案1】:

    请参阅 MSDN 文档以获取 WM_QUERYENDSESSIONWM_ENDSESSION 消息; WM_ENDSESSION 消息的参数将告诉您您的应用程序是正常退出还是因为 Windows 正在关闭。您可以通过覆盖表单中的 WndProc 方法来处理这些消息,例如:

    public partial class MainForm : Form
    {
        private const int WM_ENDSESSION = 0x0016;
        private const uint ENDSESSION_CLOSEAPP = 0x1;
        private const uint ENDSESSION_CRITICAL = 0x40000000;
        private const uint ENDSESSION_LOGOFF = 0x80000000;
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_ENDSESSION)
            {
                var sessionEnding = m.WParam.ToInt32() != 0;
    
                if ((m.LParam.ToInt64() & ENDSESSION_CLOSEAPP) == ENDSESSION_CLOSEAPP)
                {
                    // App closing
                }
                if ((m.LParam.ToInt64() & ENDSESSION_CRITICAL) == ENDSESSION_CRITICAL)
                {
                    // Critical error
                }
                if ((m.LParam.ToInt64() & ENDSESSION_LOGOFF) == ENDSESSION_LOGOFF)
                {
                    // User logging off
                }
    
                m.Result = IntPtr.Zero;
            }
            else
            {
                base.WndProc(ref m);
            }
        }
    }
    

    【讨论】:

    • 我知道它很旧,但是...问题说“没有表格”...
    【解决方案2】:

    这个怎么样?

         AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
    

    然后

      /// <summary>
      /// Method called when the process is exiting.
      /// </summary>
      private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
      {
         // do something
      }
    

    【讨论】:

    • 这对我不起作用... :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    相关资源
    最近更新 更多