主页 > 编程资料 > C# >
发布时间:2015-09-26 作者:网络 阅读:226次
有很多的软件都实现了自动关机这样的功能。前一阵在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 description for TimerComputerShutdown.
///

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;
///
/// Required designer variable.
///

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(,',',');

}

///
/// Clean up any resources being used.
///

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose(,',',');
}
}
base.Dispose( disposing ,',',');
}

#region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

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

///
/// The main entry point for the application.
///

[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{
///
/// Specifies the type of restart options that an application can use.
///

public enum RestartOptions {
///
/// Shuts down all processes running in the security context of the process that called the ExitWindowsEx function. Then it logs the user off.
///

LogOff = 0,
///
/// Shuts down the system and turns off the power. The system must support the power-off feature.
///

PowerOff = 8,
///
/// Shuts down the system and then restarts the system.
///

Reboot = 2,
///
/// 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.
///

ShutDown = 1,
///
/// Suspends the system.
///

Suspend = -1,
///
/// Hibernates the system.
///

Hibernate = -2,
}
///
/// 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.
///

[StructLayout(LayoutKind.Sequential, Pack=1)]
internal struct LUID {
///
/// The low order part of the 64 bit value.
///

public int LowPart;
///
/// The high order part of the 64 bit value.
///

public int HighPart;
}
///
/// The LUID_AND_ATTRIBUTES structure represents a locally unique identifier (LUID) and its attributes.
///

[StructLayout(LayoutKind.Sequential, Pack=1)]
internal struct LUID_AND_ATTRIBUTES {
///
/// Specifies an LUID value.
///

public LUID pLuid;
///
/// 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.
///

public int Attributes;
}
///
/// The TOKEN_PRIVILEGES structure contains information about a set of privileges for an access token.
///

[StructLayout(LayoutKind.Sequential, Pack=1)]
internal struct TOKEN_PRIVILEGES {
///
/// Specifies the number of entries in the Privileges array.
///

public int PrivilegeCount ;
///
/// Specifies an array of LUID_AND_ATTRIBUTES structures. Each structure contains the LUID and attributes of a privilege.
///

public LUID_AND_ATTRIBUTES Privileges ;
}
///
/// Implements methods to exit Windows.
///

public class WindowsController {
/// Required to enable or disable the privileges in an access token.
private const int TOKEN_ADJUST_PRIVILEGES = 0x20;
/// Required to query an access token.
private const int TOKEN_QUERY = 0x8;
/// The privilege is enabled.
private const int SE_PRIVILEGE_ENABLED = 0x2;
/// Specifies that the function should search the system message-table resource(s) for the requested message.
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x1000;
/// 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.
private const int EWX_FORCE = 4;
///
/// The LoadLibrary function maps the specified executable module into the address space of the calling process.
///

/// 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.
/// If the function succeeds, the return value is a handle to the module.


If the function fails, the return value is NULL. To get extended error information, call Marshal.GetLastWin32Error.

[ DllImport( "kernel32.dll", EntryPoint="LoadLibraryA", CharSet=CharSet.Ansi )]
private static extern IntPtr LoadLibrary(string lpLibFileName,',',');
///
/// 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.
///

/// Handle to the loaded DLL module. The LoadLibrary or GetModuleHandle function returns this handle.
/// If the function succeeds, the return value is nonzero.


If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.

[ DllImport( "kernel32.dll", EntryPoint="FreeLibrary", CharSet=CharSet.Ansi )]
private static extern int FreeLibrary(IntPtr hLibModule,',',');
///
/// The GetProcAddress function retrieves the address of an exported function or variable from the specified dynamic-link library (DLL).
///

/// Handle to the DLL module that contains the function or variable. The LoadLibrary or GetModuleHandle function returns this handle.
/// 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.
/// If the function succeeds, the return value is the address of the exported function or variable.


If the function fails, the return value is NULL. To get extended error information, call Marshal.GetLastWin32Error.

[ DllImport( "kernel32.dll", EntryPoint="GetProcAddress", CharSet=CharSet.Ansi )]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName,',',');
///
/// 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.
///

/// Specifies the state of the system. If TRUE, the system hibernates. If FALSE, the system is suspended.
/// 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.
/// If TRUE, the system disables all wake events. If FALSE, any system wake events remain enabled.
/// If the function succeeds, the return value is nonzero.


If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.

[ DllImport( "powrprof.dll", EntryPoint="SetSuspendState", CharSet=CharSet.Ansi )]
private static extern int SetSuspendState(int Hibernate, int ForceCritical, int DisableWakeEvent,',',');
///
/// The OpenProcessToken function opens the access token associated with a process.
///

/// Handle to the process whose access token is opened.
/// 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.
/// Pointer to a handle identifying the newly-opened access token when the function returns.
/// If the function succeeds, the return value is nonzero.


If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.

[ DllImport( "advapi32.dll", EntryPoint="OpenProcessToken", CharSet=CharSet.Ansi )]
private static extern int OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle,',',');
///
/// The LookupPrivilegeValue function retrieves the locally unique identifier (LUID) used on a specified system to locally represent the specified privilege name.
///

/// 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.
/// 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".
/// Pointer to a variable that receives the locally unique identifier by which the privilege is known on the system, specified by the lpSystemName parameter.
/// If the function succeeds, the return value is nonzero.


If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.

[ DllImport( "advapi32.dll", EntryPoint="LookupPrivilegeValueA", CharSet=CharSet.Ansi )]
private static extern int LookupPrivilegeValue(string lpSystemName, string lpName, ref LUID lpLuid,',',');
///
/// 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.
///

/// 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.
/// 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.
/// 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.
/// 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.
/// 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.
/// 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.
/// If the function succeeds, the return value is nonzero. To determine whether the function adjusted all of the specified privileges, call Marshal.GetLastWin32Error.
[ 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,',',');
///
/// 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.
///

/// Specifies the type of shutdown.
/// This parameter is ignored.
/// If the function succeeds, the return value is nonzero.


If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.

[ DllImport( "user32.dll", EntryPoint="ExitWindowsEx", CharSet=CharSet.Ansi )]
private static extern int ExitWindowsEx(int uFlags, int dwReserved,',',');
///
/// 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.
///

/// 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.
/// Specifies the location of the message definition. The type of this parameter depends upon the settings in the dwFlags parameter.
/// Specifies the message identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING.
/// Specifies the language identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING.
/// 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.
/// 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.
/// 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.
/// If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character.


If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error.

[ 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,',',');
///
/// Exits windows (and tries to enable any required access rights, if necesarry).
///

/// One of the RestartOptions values that specifies how to exit windows.
/// True if the exit has to be forced, false otherwise.
/// There was an error while requesting a required privilege.
/// The requested exit method is not supported on this platform.
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;
}
}
///
/// Exits windows (and tries to enable any required access rights, if necesarry).
///

/// One of the RestartOptions values that specifies how to exit windows.
/// True if the exit has to be forced, false otherwise.
/// This method cannot hibernate or suspend the system.
/// There was an error while requesting a required privilege.
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()),',',');
}
///
/// Tries to enable the specified privilege.
///

/// The privilege to enable.
/// There was an error while requesting a required privilege.
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()),',',');
}
///
/// Suspends or hibernates the system.
///

/// True if the system has to hibernate, false if the system has to be suspended.
/// True if the exit has to be forced, false otherwise.
/// The requested exit method is not supported on this platform.
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,',',');
}
///
/// Checks whether a specified method exists on the local computer.
///

/// The library that holds the method.
/// The entry point of the requested method.
/// True if the specified method is present, false otherwise.
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;
}
///
/// Formats an error number into an error message.
///

/// The error number to convert.
/// A string representation of the specified error number.
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(,',',');
}
}
///
/// The exception that is thrown when an error occures when requesting a specific privilege.
///

public class PrivilegeException : Exception {
///
/// Initializes a new instance of the PrivilegeException class.
///

public PrivilegeException () : base() {}
///
/// Initializes a new instance of the PrivilegeException class with a specified error message.
///

/// The message that describes the error.
public PrivilegeException (string message ) :base(message) {}
}
}



关键字词: