C# 托盘应用程序允许系统在登录或退出时终止我的程序

C# 托盘应用程序允许系统在登录或退出时终止我的程序,c#,windows,workflow-foundation,exit,tray,C#,Windows,Workflow Foundation,Exit,Tray,我的程序是从windows开始的,我有这样的代码来防止用户点击退出按钮时退出应用程序: protected override void OnClosing(CancelEventArgs e) { this.ShowInTaskbar = false; e.Cancel = true; this.Hide(); } 它工作得很好,但当我想关掉电脑的时候,每次我都会看到“一个或多个应用程序无法退出”这样的屏幕。取消-退出,尽

我的程序是从windows开始的,我有这样的代码来防止用户点击退出按钮时退出应用程序:

    protected override void OnClosing(CancelEventArgs e)
    {
        this.ShowInTaskbar = false;
        e.Cancel = true;
        this.Hide();
    }
它工作得很好,但当我想关掉电脑的时候,每次我都会看到“一个或多个应用程序无法退出”这样的屏幕。取消-退出,尽管如此

如何允许windows正常退出我的应用程序,但在单击红色退出按钮时又阻止用户退出应用程序?

请参阅

在事件处理程序中,设置一个类似于
sessionedd
的布尔值,并在OnClosing测试中设置该值:

if (!sessionEnded)
{
    e.Cancel = true;
    this.Hide();
}
这有助于(感谢CodeCaster):


你最好自己发布一个答案,而不是在你的问题上添加答案。。。。
    private static int WM_QUERYENDSESSION = 0x11;
    private static bool systemShutdown = false;
    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        if (m.Msg == WM_QUERYENDSESSION)
        {
            systemShutdown = true;
        }

        // If this is WM_QUERYENDSESSION, the closing event should be
        // raised in the base WndProc.
        base.WndProc(ref m);

    } //WndProc 

    protected override void OnClosing(CancelEventArgs e)
    {
        this.ShowInTaskbar = false;
        if (!systemShutdown)
        {
            e.Cancel = true;
            this.Hide();
        }
    }