防止 Windows 关闭 [英] Preventing Windows from shutting down

查看:32
本文介绍了防止 Windows 关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 windows 窗体,如果用户尝试关闭 windows 或尝试在进程完成之前关闭应用程序(用户忘记完成进程),如果用户按下确定,我想停止关闭窗口并让用户完成进程,我确实在网上找到了一些代码来这样做,但它在 VB 中而不是在 c# 中

I am using windows form,I want to display the message to the user that the process is not complete if the user tries to shut down the windows or tries to closes the application before completion of process(the user forgot to complete the process),if the user presses OK i want to stop the window from shutting down and let the user complete the process,I did find some code on the net to do so but it is in VB not in c#

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason.Equals(CloseReason.WindowsShutDown))
    {
        Microsoft.VisualBasic.Interaction.Shell("shutdown -a", AppWinStyle.MinimizedFocus, false, -1);
        MessageBox.Show("Shutdown process cancelled!");
    }
}

推荐答案

最好使用这段代码片段,根据您的要求使用 e.Cancel :

Better to use this piece of code snippet instead, play with e.Cancel as per your requirement:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason.Equals(CloseReason.WindowsShutDown))
    {
       if (MessageBox.Show("You are closing this app.\n\nAre you sure you wish to exit ?", "Warning: Not Submitted", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop) == DialogResult.Yes)
           return;    
       else    
           e.Cancel = true;
    }
}

参考:系统事件.SessionEnding 事件

在用户尝试注销或关闭系统时发生.

Occurs when the user is trying to log off or shut down the system.

这篇关于防止 Windows 关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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