using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using System.Text;
namespace timercomputershutdown
{
/// <summary>
/// summary description for timercomputershutdown.
/// </summary>
public class timercomputershutdown : System.Windows.Forms.Form
{
private System.Windows.Forms.Label labelwhatdoyouwantthecomputertodo;
private System.Windows.Forms.ComboBox combobox;
private System.Windows.Forms.Label labelselectdatetimetoshutdowncomputer;
private System.Windows.Forms.DateTimePicker datetimepicker;
private System.Windows.Forms.Label labeldatetimenow;
private System.Windows.Forms.Label labeldatetimeshutdown;
private System.Windows.Forms.Label labelnow;
private System.Windows.Forms.Label labelshutdown;
private System.Windows.Forms.Panel panelparent;
private System.Windows.Forms.Panel panelchild;
private System.Windows.Forms.CheckBox checkbox;
private System.Windows.Forms.Button buttoncancel;
private System.Windows.Forms.Button buttoninvoke;
/// <summary>
/// required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Threading.ThreadStart threadstart;
private System.Threading.Thread thread;
[DllImport("user32.dll")]
private static extern
bool setforegroundwindow(IntPtr hwnd);
[DllImport("user32.dll")]
private static extern
bool showwindowasync(IntPtr hwnd, int ncmdshow);
[DllImport("user32.dll")]
private static extern
bool isiconic(IntPtr hwnd);
private const int sw_hide = 0;
private const int sw_shownormal = 1;
private const int sw_showminimized = 2;
private const int sw_showmaximized = 3;
private const int sw_shownoactivate = 4;
private const int sw_restore = 9;
private const int sw_showdefault = 10;
public timercomputershutdown()
{
initializecomponent();
}
/// <summary>
/// clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region windows form designer generated code
/// <summary>
/// required method for designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void initializecomponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(timercomputershutdown));
this.labelwhatdoyouwantthecomputertodo = new System.Windows.Forms.Label();
this.combobox = new System.Windows.Forms.ComboBox();
this.labelselectdatetimetoshutdowncomputer = new System.Windows.Forms.Label();
this.datetimepicker = new System.Windows.Forms.DateTimePicker();
this.labeldatetimenow = new System.Windows.Forms.Label();
this.labeldatetimeshutdown = new System.Windows.Forms.Label();
this.labelnow = new System.Windows.Forms.Label();
this.labelshutdown = new System.Windows.Forms.Label();
this.panelparent = new System.Windows.Forms.Panel();
this.panelchild = new System.Windows.Forms.Panel();
this.buttoncancel = new System.Windows.Forms.Button();
this.buttoninvoke = new System.Windows.Forms.Button();
this.checkbox = new System.Windows.Forms.CheckBox();
this.panelparent.SuspendLayout();
this.panelchild.SuspendLayout();
this.SuspendLayout();
//
// labelwhatdoyouwantthecomputertodo
//
this.labelwhatdoyouwantthecomputertodo.Location = new System.Drawing.Point(8, 8);
this.labelwhatdoyouwantthecomputertodo.Name = "labelwhatdoyouwantthecomputertodo";
this.labelwhatdoyouwantthecomputertodo.Size = new System.Drawing.Size(216, 16);
this.labelwhatdoyouwantthecomputertodo.TabIndex = 9;
this.labelwhatdoyouwantthecomputertodo.Text = "选择任务:";
this.labelwhatdoyouwantthecomputertodo.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// combobox
//
this.combobox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.combobox.Items.AddRange(new object[] {
"关机",
"重启",
"待机",
"睡眠",
"注销"});
this.combobox.Location = new System.Drawing.Point(184, 8);
this.combobox.Name = "combobox";
this.combobox.Size = new System.Drawing.Size(112, 21);
this.combobox.TabIndex = 0;
this.combobox.SelectedIndexChanged += new System.EventHandler(this.combobox_selectedindexchanged);
//
// labelselectdatetimetoshutdowncomputer
//
this.labelselectdatetimetoshutdowncomputer.Location = new System.Drawing.Point(8, 32);
this.labelselectdatetimetoshutdowncomputer.Name = "labelselectdatetimetoshutdowncomputer";
this.labelselectdatetimetoshutdowncomputer.Size = new System.Drawing.Size(144, 16);
this.labelselectdatetimetoshutdowncomputer.TabIndex = 7;
this.labelselectdatetimetoshutdowncomputer.Text = "选择任务时间: ";
this.labelselectdatetimetoshutdowncomputer.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// datetimepicker
//
this.datetimepicker.CalendarFont = new System.Drawing.Font("tahoma", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.datetimepicker.Cursor = System.Windows.Forms.Cursors.Arrow;
this.datetimepicker.Font = new System.Drawing.Font("tahoma", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.datetimepicker.Format = System.Windows.Forms.DateTimePickerFormat.Time;
this.datetimepicker.Location = new System.Drawing.Point(184, 32);
this.datetimepicker.Name = "datetimepicker";
this.datetimepicker.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.datetimepicker.Size = new System.Drawing.Size(112, 21);
this.datetimepicker.TabIndex = 1;
this.datetimepicker.Value = new System.DateTime(2002, 9, 27, 0, 0, 0, 0);
this.datetimepicker.ValueChanged += new System.EventHandler(this.datetimepicker_valuechanged);
//
// labeldatetimenow
//
this.labeldatetimenow.Font = new System.Drawing.Font("tahoma", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.labeldatetimenow.Location = new System.Drawing.Point(8, 8);
this.labeldatetimenow.Name = "labeldatetimenow";
this.labeldatetimenow.Size = new System.Drawing.Size(120, 16);
this.labeldatetimenow.TabIndex = 4;
this.labeldatetimenow.Text = "当前时间:";
this.labeldatetimenow.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labeldatetimeshutdown
//
this.labeldatetimeshutdown.Font = new System.Drawing.Font("tahoma", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.labeldatetimeshutdown.Location = new System.Drawing.Point(8, 32);
this.labeldatetimeshutdown.Name = "labeldatetimeshutdown";
this.labeldatetimeshutdown.Size = new System.Drawing.Size(120, 16);
this.labeldatetimeshutdown.TabIndex = 5;
this.labeldatetimeshutdown.Text = "任务时间:";
this.labeldatetimeshutdown.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// labelnow
//
this.labelnow.Font = new System.Drawing.Font("tahoma", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.labelnow.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelnow.Location = new System.Drawing.Point(136, 8);
this.labelnow.Name = "labelnow";
this.labelnow.Size = new System.Drawing.Size(136, 16);
this.labelnow.TabIndex = 1;
this.labelnow.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// labelshutdown
//
this.labelshutdown.Font = new System.Drawing.Font("tahoma", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.labelshutdown.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelshutdown.Location = new System.Drawing.Point(136, 32);
this.labelshutdown.Name = "labelshutdown";
this.labelshutdown.Size = new System.Drawing.Size(136, 16);
this.labelshutdown.TabIndex = 8;
this.labelshutdown.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// panelparent
//
this.panelparent.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelparent.Controls.Add(this.panelchild);
this.panelparent.Location = new System.Drawing.Point(8, 60);
this.panelparent.Name = "panelparent";
this.panelparent.Size = new System.Drawing.Size(288, 60);
this.panelparent.TabIndex = 6;
//
// panelchild
//
this.panelchild.Controls.Add(this.labelnow);
this.panelchild.Controls.Add(this.labelshutdown);
this.panelchild.Controls.Add(this.labeldatetimeshutdown);
this.panelchild.Controls.Add(this.labeldatetimenow);
this.panelchild.Location = new System.Drawing.Point(0, 0);
this.panelchild.Name = "panelchild";
this.panelchild.Size = new System.Drawing.Size(280, 56);
this.panelchild.TabIndex = 8;
//
// buttoncancel
//
this.buttoncancel.Cursor = System.Windows.Forms.Cursors.Hand;
this.buttoncancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttoncancel.Font = new System.Drawing.Font("tahoma", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.buttoncancel.Location = new System.Drawing.Point(176, 128);
this.buttoncancel.Name = "buttoncancel";
this.buttoncancel.Size = new System.Drawing.Size(56, 23);
this.buttoncancel.TabIndex = 4;
this.buttoncancel.Text = "取消&c";
this.buttoncancel.Click += new System.EventHandler(this.buttoncancel_click);
//
// buttoninvoke
//
this.buttoninvoke.Cursor = System.Windows.Forms.Cursors.Hand;
this.buttoninvoke.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttoninvoke.Font = new System.Drawing.Font("tahoma", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.buttoninvoke.Location = new System.Drawing.Point(240, 128);
this.buttoninvoke.Name = "buttoninvoke";
this.buttoninvoke.Size = new System.Drawing.Size(56, 23);
this.buttoninvoke.TabIndex = 3;
this.buttoninvoke.Text = "确定&o";
this.buttoninvoke.Click += new System.EventHandler(this.buttoninvoke_click);
//
// checkbox
//
this.checkbox.Cursor = System.Windows.Forms.Cursors.Hand;
this.checkbox.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.checkbox.Location = new System.Drawing.Point(8, 128);
this.checkbox.Name = "checkbox";
this.checkbox.Size = new System.Drawing.Size(66, 24);
this.checkbox.TabIndex = 2;
this.checkbox.Text = "强制&b";
//
// timercomputershutdown
//
//this.autoscalebasesize = new System.Drawing.Size(5, 14);1.x
//this.AutoScaleFactor this.AutoScaleDimensions this.AutoScaleMode this.PerformAutoScale 2.0
this.AutoScaleMode = AutoScaleMode.Dpi;
this.BackColor = System.Drawing.Color.GhostWhite;
this.ClientSize = new System.Drawing.Size(306, 159);
this.Controls.Add(this.checkbox);
this.Controls.Add(this.combobox);
this.Controls.Add(this.labelwhatdoyouwantthecomputertodo);
this.Controls.Add(this.panelparent);
this.Controls.Add(this.buttoncancel);
this.Controls.Add(this.buttoninvoke);
this.Controls.Add(this.datetimepicker);
this.Controls.Add(this.labelselectdatetimetoshutdowncomputer);
this.Font = new System.Drawing.Font("tahoma", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)new Icon("Logo.ico"));//(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "timercomputershutdown";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "timer computer shutdown";
this.TopMost = true;
this.Load += new System.EventHandler(this.timercomputershutdown_load);
this.panelparent.ResumeLayout(false);
this.panelchild.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// the main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new timercomputershutdown());
}
private void timercomputershutdown_load(object sender, System.EventArgs e)
{
this.threadstart = new System.Threading.ThreadStart(application_tick);
this.thread = new System.Threading.Thread(threadstart);
this.panelchild.Visible = false;
this.datetimepicker.Value = System.DateTime.Now;
}
protected override void OnClosing(CancelEventArgs e)
{
try
{
if (this.thread.IsAlive)
{
this.thread.Abort();
this.thread.Join();
}
}
catch (System.Threading.ThreadAbortException threadabortexception)
{
string strthreadabortexception = threadabortexception.ToString();
System.Threading.Thread.ResetAbort();
}
catch (System.Exception exception)
{
string strexception = exception.ToString();
}
finally
{
System.Windows.Forms.Application.Exit();
}
base.OnClosing(e);
}
public void computer_shutdown()
{
if (this.checkbox.Checked)
{
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process processparent in processes)
{
System.Diagnostics.Process[] processnames = System.Diagnostics.Process.GetProcessesByName(processparent.ProcessName);
foreach (System.Diagnostics.Process processchild in processnames)
{
try
{
System.IntPtr hwnd = processchild.MainWindowHandle;
if (isiconic(hwnd))
{
showwindowasync(hwnd, sw_restore);
}
setforegroundwindow(hwnd);
if (!(processchild.MainWindowTitle.Equals(this.Text)))
{
processchild.CloseMainWindow();
processchild.Kill();
processchild.WaitForExit();
}
}
catch (System.Exception exception)
{
string strexception = exception.ToString();
}
}
}
}
System.Windows.Forms.Application.Exit();
switch (this.combobox.SelectedIndex)
{
case 0:
windowscontroller.exitwindows(restartoptions.poweroff, false);
break;
case 1:
windowscontroller.exitwindows(restartoptions.reboot, false);
break;
case 2:
windowscontroller.exitwindows(restartoptions.suspend, false);
break;
case 3:
windowscontroller.exitwindows(restartoptions.hibernate, false);
break;
case 4:
windowscontroller.exitwindows(restartoptions.logoff, false);
break;
}
}
private void combobox_selectedindexchanged(object sender, System.EventArgs e)
{
this.labelselectdatetimetoshutdowncomputer.Text = "选择任务" + " " + this.combobox.SelectedItem.ToString() + " " + "时间:";
this.labeldatetimeshutdown.Text = "任务时间" + " " + this.combobox.SelectedItem.ToString() + ":";
}
public bool datetimepicker_validated()
{
if (this.datetimepicker.Value.CompareTo(System.DateTime.Now) < 0)
{
//error error = new error();
//error.showdialog();
this.datetimepicker.Value = System.DateTime.Now;
return false;
}
else
{
return true;
}
}
private void datetimepicker_valuechanged(object sender, System.EventArgs e)
{
this.labelshutdown.Text = this.datetimepicker.Value.ToString();
}
public void application_tick()
{
while (!(this.labelnow.Text.ToString().Equals(this.datetimepicker.Value.ToString())))
{
this.labelnow.Text = System.DateTime.Now.ToString();
}
this.computer_shutdown();
}
private void buttoncancel_click(object sender, System.EventArgs e)
{
try
{
if (this.thread.IsAlive)
{
this.thread.Abort();
this.thread.Join();
}
}
catch (System.Threading.ThreadStateException threadstateexception)
{
System.Threading.Thread.ResetAbort();
string strthreadstateexception = threadstateexception.ToString();
}
catch (System.Exception exception)
{
string strexception = exception.ToString();
}
finally
{
System.Windows.Forms.Application.Exit();
}
}
private void buttoninvoke_click(object sender, System.EventArgs e)
{
if (this.datetimepicker_validated())
{
this.thread.Start();
this.combobox.Enabled = false;
this.datetimepicker.Enabled = false;
this.panelchild.Visible = true;
this.buttoninvoke.Enabled = false;
}
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// timercomputershutdown
//
this.ClientSize = new System.Drawing.Size(292, 273);
this.Name = "timercomputershutdown";
this.ResumeLayout(false);
}
}
}
//using System;
//using System.Text;
//using System.Diagnostics;
//using System.runtime.interopservices;
namespace timercomputershutdown
{
/// <summary>
/// specifies the type of restart options that an application can use.
/// </summary>
public enum restartoptions
{
/// <summary>
/// shuts down all processes running in the security context of the process that called the ExitWindowsEx function. then it logs the user off.
/// </summary>
logoff = 0,
/// <summary>
/// shuts down the System and turns off the power. the System must support the power-off feature.
/// </summary>
poweroff = 8,
/// <summary>
/// shuts down the System and then restarts the System.
/// </summary>
reboot = 2,
/// <summary>
/// shuts down the System to a point at which it is safe to turn off the power. all file buffers have been flushed to disk, and all running processes have stopped. if the System supports the power-off feature, the power is also turned off.
/// </summary>
shutdown = 1,
/// <summary>
/// suspends the System.
/// </summary>
suspend = -1,
/// <summary>
/// hibernates the System.
/// </summary>
hibernate = -2,
}
/// <summary>
/// an luid is a 64-bit value guaranteed to be unique only on the System on which it was generated. the uniqueness of a locally unique identifier (luid) is guaranteed only until the System is restarted.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct luid
{
/// <summary>
/// the low order part of the 64 bit value.
/// </summary>
public int lowpart;
/// <summary>
/// the high order part of the 64 bit value.
/// </summary>
public int highpart;
}
/// <summary>
/// the luid_and_attributes structure represents a locally unique identifier (luid) and its attributes.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct luid_and_attributes
{
/// <summary>
/// specifies an luid value.
/// </summary>
public luid pluid;
/// <summary>
/// specifies attributes of the luid. this value contains up to 32 one-bit flags. its meaning is dependent on the definition and use of the luid.
/// </summary>
public int attributes;
}
/// <summary>
/// the token_privileges structure contains information about a set of privileges for an access token.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct token_privileges
{
/// <summary>
/// specifies the number of entries in the privileges array.
/// </summary>
public int privilegecount;
/// <summary>
/// specifies an array of luid_and_attributes structures. each structure contains the luid and attributes of a privilege.
/// </summary>
public luid_and_attributes privileges;
}
/// <summary>
/// implements methods to exit windows.
/// </summary>
public class windowscontroller
{
/// <summary>required to enable or disable the privileges in an access token.</summary>
private const int token_adjust_privileges = 0x20;
/// <summary>required to query an access token.</summary>
private const int token_query = 0x8;
/// <summary>the privilege is enabled.</summary>
private const int se_privilege_enabled = 0x2;
/// <summary>specifies that the function should search the System message-table resource(s) for the requested message.</summary>
private const int format_message_from_System = 0x1000;
/// <summary>forces processes to terminate. when this flag is set, the System does not send the wm_queryendsession and wm_endsession messages. this can cause the applications to lose data. therefore, you should only use this flag in an emergency.</summary>
private const int ewx_force = 4;
/// <summary>
/// the LoadLibrary function maps the specified executable module into the address space of the calling Process.
/// </summary>
/// <param name="lplibfilename">pointer to a null-terminated string that names the executable module (either a .dll or .exe file). the name specified is the file name of the module and is not related to the name stored in the library module itself, as specified by the library keyword in the module-definition (.def) file.</param>
/// <returns>if the function succeeds, the return value is a handle to the module.<br></br><br>if the function fails, the return value is null. to get extended error information, call Marshal.getlastwin32error.</br></returns>
[DllImport("kernel32.dll", EntryPoint = "LoadLibrary", CharSet = CharSet.Ansi)]
private static extern IntPtr LoadLibrary(string lplibfilename);
/// <summary>
/// the FreeLibrary function decrements the reference count of the loaded dynamic-link library (dll). when the reference count reaches zero, the module is unmapped from the address space of the calling process and the handle is no longer valid.
/// </summary>
/// <param name="hlibmodule">handle to the loaded dll module. the LoadLibrary or getmodulehandle function returns this handle.</param>
/// <returns>if the function succeeds, the return value is nonzero.<br></br><br>if the function fails, the return value is zero. to get extended error information, call Marshal.getlastwin32error.</br></returns>
[DllImport("kernel32.dll", EntryPoint = "FreeLibrary", CharSet = CharSet.Ansi)]
private static extern int FreeLibrary(IntPtr hlibmodule);
/// <summary>
/// the GetProcAddress function retrieves the address of an exported function or variable from the specified dynamic-link library (dll).
/// </summary>
/// <param name="hmodule">handle to the dll module that contains the function or variable. the LoadLibrary or getmodulehandle function returns this handle.</param>
/// <param name="lpprocname">pointer to a null-terminated string containing the function or variable name, or the functions ordinal value. if this parameter is an ordinal value, it must be in the low-order word; the high-order word must be zero.</param>
/// <returns>if the function succeeds, the return value is the address of the exported function or variable.<br></br><br>if the function fails, the return value is null. to get extended error information, call Marshal.getlastwin32error.</br></returns>
[DllImport("kernel32.dll", EntryPoint = "GetProcAddress", CharSet = CharSet.Ansi)]
private static extern IntPtr GetProcAddress(IntPtr hmodule, string lpprocname);
/// <summary>
/// the SetSuspendState function suspends the System by shutting power down. depending on the hibernate parameter, the System either enters a suspend (sleep) state or hibernation (s4). if the forceflag parameter is true, the System suspends operation immediately; if it is false, the System requests permission from all applications and device drivers before doing so.
/// </summary>
/// <param name="hibernate">specifies the state of the System. if true, the System hibernates. if false, the System is suspended.</param>
/// <param name="forcecritical">forced suspension. if true, the function broadcasts a pbt_apmsuspend event to each application and driver, then immediately suspends operation. if false, the function broadcasts a pbt_apmquerysuspend event to each application to request permission to suspend operation.</param>
/// <param name="disablewakeevent">if true, the System disables all wake events. if false, any System wake events remain enabled.</param>
/// <returns>if the function succeeds, the return value is nonzero.<br></br><br>if the function fails, the return value is zero. to get extended error information, call Marshal.getlastwin32error.</br></returns>
[DllImport("powrprof.dll", EntryPoint = "SetSuspendState", CharSet = CharSet.Ansi)]
private static extern int SetSuspendState(int hibernate, int forcecritical, int disablewakeevent);
/// <summary>
/// the OpenProcessToken function opens the access token associated with a Process.
/// </summary>
/// <param name="processhandle">handle to the process whose access token is opened.</param>
/// <param name="desiredaccess">specifies an access mask that specifies the requested types of access to the access token. these requested access types are compared with the tokens discretionary access-control list (dacl) to determine which accesses are granted or denied.</param>
/// <param name="tokenhandle">pointer to a handle identifying the newly-opened access token when the function returns.</param>
/// <returns>if the function succeeds, the return value is nonzero.<br></br><br>if the function fails, the return value is zero. to get extended error information, call Marshal.getlastwin32error.</br></returns>
[DllImport("advapi32.dll", EntryPoint = "OpenProcessToken", CharSet = CharSet.Ansi)]
private static extern int OpenProcessToken(IntPtr processhandle, int desiredaccess, ref IntPtr tokenhandle);
/// <summary>
/// the LookupPrivilegeValue function retrieves the locally unique identifier (luid) used on a specified System to locally represent the specified privilege name.
/// </summary>
/// <param name="lpSystemname">pointer to a null-terminated string specifying the name of the System on which the privilege name is looked up. if a null string is specified, the function attempts to find the privilege name on the local System.</param>
/// <param name="lpname">pointer to a null-terminated string that specifies the name of the privilege, as defined in the winnt.h header file. for example, this parameter could specify the constant se_security_name, or its corresponding string, "sesecurityprivilege".</param>
/// <param name="lpluid">pointer to a variable that receives the locally unique identifier by which the privilege is known on the System, specified by the lpSystemname parameter.</param>
/// <returns>if the function succeeds, the return value is nonzero.<br></br><br>if the function fails, the return value is zero. to get extended error information, call Marshal.getlastwin32error.</br></returns>
[DllImport("advapi32.dll", EntryPoint = "LookupPrivilegeValue", CharSet = CharSet.Ansi)]
private static extern int LookupPrivilegeValue(string lpSystemname, string lpname, ref luid lpluid);
/// <summary>
/// the AdjustTokenPrivileges function enables or disables privileges in the specified access token. enabling or disabling privileges in an access token requires token_adjust_privileges access.
/// </summary>
/// <param name="tokenhandle">handle to the access token that contains the privileges to be modified. the handle must have token_adjust_privileges access to the token. if the previousstate parameter is not null, the handle must also have token_query access.</param>
/// <param name="disableallprivileges">specifies whether the function disables all of the tokens privileges. if this value is true, the function disables all privileges and ignores the newstate parameter. if it is false, the function modifies privileges based on the information pointed to by the newstate parameter.</param>
/// <param name="newstate">pointer to a token_privileges structure that specifies an array of privileges and their attributes. if the disableallprivileges parameter is false, AdjustTokenPrivileges enables or disables these privileges for the token. if you set the se_privilege_enabled attribute for a privilege, the function enables that privilege; otherwise, it disables the privilege. if disableallprivileges is true, the function ignores this parameter.</param>
/// <param name="bufferlength">specifies the size, in bytes, of the buffer pointed to by the previousstate parameter. this parameter can be zero if the previousstate parameter is null.</param>
/// <param name="previousstate">pointer to a buffer that the function fills with a token_privileges structure that contains the previous state of any privileges that the function modifies. this parameter can be null.</param>
/// <param name="returnlength">pointer to a variable that receives the required size, in bytes, of the buffer pointed to by the previousstate parameter. this parameter can be null if previousstate is null.</param>
/// <returns>if the function succeeds, the return value is nonzero. to determine whether the function adjusted all of the specified privileges, call Marshal.getlastwin32error.</returns>
[DllImport("advapi32.dll", EntryPoint = "AdjustTokenPrivileges", CharSet = CharSet.Ansi)]
private static extern int AdjustTokenPrivileges(IntPtr tokenhandle, int disableallprivileges, ref token_privileges newstate, int bufferlength, ref token_privileges previousstate, ref int returnlength);
/// <summary>
/// the ExitWindowsEx function either logs off the current user, shuts down the System, or shuts down and restarts the System. it sends the wm_queryendsession message to all applications to determine if they can be terminated.
/// </summary>
/// <param name="uflags">specifies the type of shutdown.</param>
/// <param name="dwreserved">this parameter is ignored.</param>
/// <returns>if the function succeeds, the return value is nonzero.<br></br><br>if the function fails, the return value is zero. to get extended error information, call Marshal.getlastwin32error.</br></returns>
[DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)]
private static extern int ExitWindowsEx(int uflags, int dwreserved);
/// <summary>
/// the FormatMessage function formats a message string. the function requires a message definition as input. the message definition can come from a buffer passed into the function. it can come from a message table resource in an already-loaded module. or the caller can ask the function to search the Systems message table resource(s) for the message definition. the function finds the message definition in a message table resource based on a message identifier and a language identifier. the function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested.
/// </summary>
/// <param name="dwflags">specifies aspects of the formatting process and how to interpret the lpsource parameter. the low-order byte of dwflags specifies how the function handles line breaks in the output buffer. the low-order byte can also specify the maximum width of a formatted output line.</param>
/// <param name="lpsource">specifies the location of the message definition. the type of this parameter depends upon the settings in the dwflags parameter.</param>
/// <param name="dwmessageid">specifies the message identifier for the requested message. this parameter is ignored if dwflags includes format_message_from_string.</param>
/// <param name="dwlanguageid">specifies the language identifier for the requested message. this parameter is ignored if dwflags includes format_message_from_string.</param>
/// <param name="lpbuffer">pointer to a buffer for the formatted (and null-terminated) message. if dwflags includes format_message_allocate_buffer, the function allocates a buffer using the localalloc function, and places the pointer to the buffer at the address specified in lpbuffer.</param>
/// <param name="nsize">if the format_message_allocate_buffer flag is not set, this parameter specifies the maximum number of tchars that can be stored in the output buffer. if format_message_allocate_buffer is set, this parameter specifies the minimum number of tchars to allocate for an output buffer. for ansi text, this is the number of bytes; for unicode text, this is the number of characters.</param>
/// <param name="arguments">pointer to an array of values that are used as insert values in the formatted message. a %1 in the format string indicates the first value in the arguments array; a %2 indicates the second argument; and so on.</param>
/// <returns>if the function succeeds, the return value is the number of tchars stored in the output buffer, excluding the terminating null character.<br></br><br>if the function fails, the return value is zero. to get extended error information, call Marshal.getlastwin32error.</br></returns>
[DllImport("user32.dll", EntryPoint = "FormatMessage", CharSet = CharSet.Ansi)]
private static extern int FormatMessage(int dwflags, IntPtr lpsource, int dwmessageid, int dwlanguageid, StringBuilder lpbuffer, int nsize, int arguments);
/// <summary>
/// exits windows (and tries to enable any required access rights, if necesarry).
/// </summary>
/// <param name="how">one of the restartoptions values that specifies how to exit windows.</param>
/// <param name="force">true if the exit has to be forced, false otherwise.</param>
/// <exception cref="privilegeexception">there was an error while requesting a required privilege.</exception>
/// <exception cref="platformnotsupportedexception">the requested exit method is not supported on this platform.</exception>
public static void exitwindows(restartoptions how, bool force)
{
switch (how)
{
case restartoptions.suspend:
suspendSystem(false, force);
break;
case restartoptions.hibernate:
suspendSystem(true, force);
break;
default:
exitwindows((int)how, force);
break;
}
}
/// <summary>
/// exits windows (and tries to enable any required access rights, if necesarry).
/// </summary>
/// <param name="how">one of the restartoptions values that specifies how to exit windows.</param>
/// <param name="force">true if the exit has to be forced, false otherwise.</param>
/// <remarks>this method cannot hibernate or suspend the System.</remarks>
/// <exception cref="privilegeexception">there was an error while requesting a required privilege.</exception>
protected static void exitwindows(int how, bool force)
{
enabletoken("seshutdownprivilege");
if (force)
how = how | ewx_force;
if (ExitWindowsEx(how, 0) == 0)
throw new privilegeexception(formaterror(Marshal.GetLastWin32Error()));
}
/// <summary>
/// tries to enable the specified privilege.
/// </summary>
/// <param name="privilege">the privilege to enable.</param>
/// <exception cref="privilegeexception">there was an error while requesting a required privilege.</exception>
protected static void enabletoken(string privilege)
{
if (!checkentrypoint("advapi32.dll", "AdjustTokenPrivileges"))
return;
IntPtr tokenhandle = IntPtr.Zero;
luid privilegeluid = new luid();
token_privileges newprivileges = new token_privileges();
token_privileges tokenprivileges;
if (OpenProcessToken(Process.GetCurrentProcess().Handle, token_adjust_privileges | token_query, ref tokenhandle) == 0)
throw new privilegeexception(formaterror(Marshal.GetLastWin32Error()));
if (LookupPrivilegeValue("", privilege, ref privilegeluid) == 0)
throw new privilegeexception(formaterror(Marshal.GetLastWin32Error()));
tokenprivileges.privilegecount = 1;
tokenprivileges.privileges.attributes = se_privilege_enabled;
tokenprivileges.privileges.pluid = privilegeluid;
int size = 4;
if (AdjustTokenPrivileges(tokenhandle, 0, ref tokenprivileges, 4 + (12 * tokenprivileges.privilegecount), ref newprivileges, ref size) == 0)
throw new privilegeexception(formaterror(Marshal.GetLastWin32Error()));
}
/// <summary>
/// suspends or hibernates the System.
/// </summary>
/// <param name="hibernate">true if the System has to hibernate, false if the System has to be suspended.</param>
/// <param name="force">true if the exit has to be forced, false otherwise.</param>
/// <exception cref="platformnotsupportedexception">the requested exit method is not supported on this platform.</exception>
protected static void suspendSystem(bool hibernate, bool force)
{
if (!checkentrypoint("powrprof.dll", "SetSuspendState"))
throw new PlatformNotSupportedException("the SetSuspendState method is not supported on this System!");
SetSuspendState((int)(hibernate ? 1 : 0), (int)(force ? 1 : 0), 0);
}
/// <summary>
/// checks whether a specified method exists on the local computer.
/// </summary>
/// <param name="library">the library that holds the method.</param>
/// <param name="method">the entry point of the requested method.</param>
/// <returns>true if the specified method is present, false otherwise.</returns>
protected static bool checkentrypoint(string library, string method)
{
IntPtr libptr = LoadLibrary(library);
if (!libptr.Equals(IntPtr.Zero))
{
if (!GetProcAddress(libptr, method).Equals(IntPtr.Zero))
{
FreeLibrary(libptr);
return true;
}
FreeLibrary(libptr);
}
return false;
}
/// <summary>
/// formats an error number into an error message.
/// </summary>
/// <param name="number">the error number to convert.</param>
/// <returns>a string representation of the specified error number.</returns>
protected static string formaterror(int number)
{
StringBuilder buffer = new StringBuilder(255);
FormatMessage(format_message_from_System, IntPtr.Zero, number, 0, buffer, buffer.Capacity, 0);
return buffer.ToString();
}
}
/// <summary>
/// the exception that is thrown when an error occures when requesting a specific privilege.
/// </summary>
public class privilegeexception : Exception
{
/// <summary>
/// initializes a new instance of the privilegeexception class.
/// </summary>
public privilegeexception() : base() { }
/// <summary>
/// initializes a new instance of the privilegeexception class with a specified error message.
/// </summary>
/// <param name="message">the message that describes the error.</param>
public privilegeexception(string message) : base(message) { }
}
}