There are a lot of software to automatically shut down such a function. The previous array saw such a program on CodeProject, sorting it, sharing it for everyone. Which implements shutdown, restart, log off and other functions .using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Windows .
namespace TimerComputerShutdown {///
[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 () {initializationComponent ();
///
#region Windows Form Designer generated code ///
this.labelWhatDoYouWantTheComputerToDo.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // comboBox // this.comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox.Items.AddRange (new object [] { "Shutdown", "restart", "standby", "sleep", "logout"}; 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.labelSelectDateTimeToShutdownCo mputer.TabIndex = 7; this.labelSelectDateTimeToShutdownComputer.Text = "Select task time:"; 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))); 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.drawin g.Size (120, 16); this.labelDateTimeNow.TabIndex = 4; this.labelDateTimeNow.Text = "Current Time:"; 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 = "task time:"; this.labelDateTimeShutdown.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // labelNow // this.labelNow.Font = new System. Drawing.font ("Tahoma", 8.25F, System.drawing.FontStyle.bold, System.drawing.graphchicsUnit.Point, (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.FLRSFLATSTYLE. 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 = "Cancel & C"; this.bu ttonCancel.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.buttonivoke.font = new system.drawing.font ("Tahoma", 8.25F, System.drawing.FontStyle.Regular, System.drawing.graphchicsUnit.point, ((System.byte) (0)) This.ButtonInvoke.location = new system.drawing.point (240, 128); this.buttonivoke.name = "ButtonInvoke"; this.ButtonInvoke.size = new system.drawing.size (56, 23); this. ButtonInvoke.tabindex = 3;
this.buttonInvoke.Text = "OK & 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 = "Forced & B"; /// TimomputershutDown // 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 .Formographersty = system.windows.forms.formbook.Windows.Forms.FormBorderstyle.fixedDialog; this.don = (("$ this.drawing.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.timomputershutdown_load); this.PanelParent.ResumeLayout (false); this.Panelchild.ResumeLayout (false); this.ResumeLayout (false);} #ENDREGION
///
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.Rsetabort ();} 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); (! (processChild.MainWindowTitle.Equals (this.Text))) if {processChild.CloseMainWindow () Processchild.kill (); processchild.waitforeXIT ();}} catch (}}) {}}}}}}}}}}}}}}}}}}}}}}
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 = "Select Task" " this.comboBox.selectedItem.Tostring () " "time:"; this.labeldatetimeshutdown.text = "task time" "" 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 {///
/// 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 {///
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x1000;. ///
ife, the return value is null. to get extended error Informati . On, call Marshal.GetLastWin32Error returns> [DllImport ( "kernel32.dll", EntryPoint = "LoadLibraryA", CharSet = CharSet.Ansi)] private static extern IntPtr LoadLibrary (string lpLibFileName); ///
Handle to the loaded DLL module. The LoadLibrary or GetModuleHandle function returns this handle. Param> ///
If the function fails, the return value is zero. To get extended error information, call Marshal.GetLastWin32Error. returns> [DllImport ( "kernel32.dll", EntryPoint = "FreeLibrary", CharSet = CharSet.Ansi)] private static extern int FreeLibrary (IntPtr hLibModule);. ///
the function fails, the return value is NULL. To get extended error information, call Marshal.GetLastWin32Error. returns> [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. /// summary> /// Specifies the state of the system. If TRUE, the system hibernates. If FALSE, the system is suspended. param> /// 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> /// If TRUE, the system disables all wake events. If FALSE, any system wake events remain enabled. param> ///
ife value is zero. TO GET Extended Error Information, Call Marshal.getlastwin32error. returns> DllImport ( "powrprof.dll", EntryPoint = "SetSuspendState", CharSet = CharSet.Ansi)] private static extern int SetSuspendState (int Hibernate, int ForceCritical, int DisableWakeEvent); ///
/ Param> /// 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 Grand or Denied. param> /// Pointer to a Handle Identifying the newly-opened access tokenhen a function returns. param> ///
ife value is zero. TO GET Extended Error Information, Call Marshal.getlastwin32error. returns> [DLLIMPORT ( "advapi32.dll", EntryPoint = "OpenProcessToken", CharSet = CharSet.Ansi)] private static extern int OpenProcessToken (IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle); ///
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> ///
ife value is zero. to get extended error information, call marshal.getlastwin32error. returns> [DLLIMPORT ("ADVAPI32. dll ", EntryPoint =" LookupPrivilegeValueA ", CharSet = CharSet.Ansi)] private static extern int LookupPrivilegeValue (string lpSystemName, string lpName, ref LUID lpLuid); ///
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> /// 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> /// 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> /// Pointer to a variable That Receives the Required size, in bytes, of the buff pinted to by the prepviousste parameter. This parameter can be NULL if PreviousState is NULL. param> ///
/// 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> / // specifies the type of shutdown. param> /// this parameter is ignored. param> ///
ife value is zero. TO GET Extended Error Information, Call Marshal.getlastwin32error. returns> [DLLIMPORT "user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)] private static extern int ExitWindowsEx (int uFlags, int dwReserved); ///
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> /// Specifies the location of the message definition. The type of this parameter depends upon the settings in the dwFlags parameter. param> /// Specifies the message identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING. param> /// Specifies the language identifier for the requested message. This parameter is ignored if dwFlags includes FORMAT_MESSAGE_FROM_STRING. param> /// 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 functio n, and places the pointer to the buffer at the address specified in lpBuffer. param> /// 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 param> /. //
If the function fails, the return value is zero . To get extended error information, call Marshal.GetLastWin32Error. 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);. ///
Break;}} ///
, 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 ()));} ///