是否有可能以编程方式阻止Windows关闭?

时间:2014-10-11 18:22:15

标签: c#

我想开发一个程序来完全控制Windows并阻止用户关闭Windows。有解决方案吗?

编程语言并不重要。

2 个答案:

答案 0 :(得分:3)

Windows Forms中执行此操作的一种非常简单的方法,C#:

private void Form1_Load(object sender, EventArgs e)
{
    this.FormClosing += Form1_FormClosing;
}

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.WindowsShutDown)
    {
        e.Cancel = true;
    }
}

这会阻止Windows关闭,如果你想要关闭或取消它,它会提示你,因为这个应用程序(Windows窗体应用程序)被阻止关闭......

参考: CloseReason Enumeration

你也可以尝试下面的代码,它可能比上面的代码更好,更有效:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.WindowsShutDown)
    {
        Process.Start("shutdown", "-a");
    }
}

参考: Cancel a Restart or Shutdown

Windows Vista之后,您无法阻止关闭。尝试这样做会导致屏幕显示某些应用程序正在阻止关闭,如果您想要关闭或取消...上面的代码将阻止您关闭,但您不应该完全阻止关闭下。

一个更好的解决方案,让您甚至可以在关闭时显示的屏幕提示中显示消息,是:

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    public extern static bool ShutdownBlockReasonCreate(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] string pwszReason);

    private bool blocked = false;

    protected override void WndProc(ref Message aMessage)
    {
        const int WM_QUERYENDSESSION = 0x0011;
        const int WM_ENDSESSION = 0x0016;

        if (blocked && (aMessage.Msg == WM_QUERYENDSESSION || aMessage.Msg == WM_ENDSESSION))
            return;

        base.WndProc(ref aMessage);
    }

    void Button1_Click(object sender, FormClosingEventArgs e)
    {
        if (ShutdownBlockReasonCreate(this.Handle, "DONT:"))
        {
            blocked = true;
            MessageBox.Show("Shutdown blocking succeeded");
        }
        else
            MessageBox.Show("Shutdown blocking failed");
    }
}

参考: Windows Vista - ShutdownBlockReasonCreate in C#

答案 1 :(得分:3)

运行gpedit.msc→计算机配置→Windows设置→安全设置→本地策略→用户权限分配→关闭系统

找到一种方法,以您选择的语言从此组策略中删除用户或组。也许有帮助:Group Policy Settings Reference for Windows and Windows Server