Reputation: 166
I want develop a program to control Windows completely and prevent users from shutting down Windows. Is there a solution?
The programming language isn't important.
Edit: users can not access power button on computer case or power cable, because of physical guards.
Upvotes: 1
Views: 6084
Reputation: 3360
A very simple way to do this in 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;
}
}
This will prevent windows from shutting down, and it will prompt you that if you want to shut down anyway or cancel it, because this application (Windows Form application) is prevented from shutting down...
Ref.: CloseReason Enumeration
You could also try the code below which is probably better and more efficient than the code above:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.WindowsShutDown)
{
Process.Start("shutdown", "-a");
}
}
Ref.: Cancel a Restart or Shutdown
After Windows Vista you can not block shut down just like that. Trying to do so will cause a screen that will ask you that some application is blocking shut down and if you want to shut down anyway or cancel... The code above will let you block the shut down, but you should not completely block shut down.
A much better solution, that lets you even display a message at the screen prompt that is shown when shut down is blocked, is:
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");
}
}
Ref.: Windows Vista - ShutdownBlockReasonCreate in C#
Upvotes: 5
Reputation: 14762
Run gpedit.msc
→ Computer Configuration → Windows Settings → Security Settings → Local Policies → User Rights Assignment → Shut down the system
Find a way to remove users or groups from this group policy in the language of your choice. Maybe helpful: Group Policy Settings Reference for Windows and Windows Server.
Upvotes: 3