有很多的软件都实现了自动关机这样的功能。前一阵在codeproject上看到一个这样的程序,整理了一下共享给大家。里面实现了关机,重启,注销等功能.
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;
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);
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)(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)
{
system.threading.thread.resetabort();
}
catch (system.exception exception)
{
}
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)
{
}
}
}
}
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();
}
catch (system.exception exception)
{
}
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;
}
}
}
}
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="loadlibrarya", 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 function's 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 token's 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="lookupprivilegevaluea", 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 token's 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 system's 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="formatmessagea", 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) {}
}
}