C# Windows 程序退出请求 (Detect Application.Exit) 无表单 [英] C# Windows Program Exit Request (Detect Application.Exit) No Forms

查看:26
本文介绍了C# Windows 程序退出请求 (Detect Application.Exit) 无表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to detect once Application.Exit was called or is there an win32 function to know when windows like to close your program, because of shutdown or anything. No Forms.

推荐答案

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

See the MSDN documentation for the WM_QUERYENDSESSION and WM_ENDSESSION messages; the parameters of the WM_ENDSESSION message will tell you if your app is exiting normally or because Windows is shutting down. You can handle these messages by overriding the WndProc method in your form, something like:

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);
        }
    }
}

这篇关于C# Windows 程序退出请求 (Detect Application.Exit) 无表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆