Click here to Skip to main content
11,569,800 members (57,646 online)
Click here to Skip to main content

Timer Computer Shutdown

, 2 Oct 2002 304.7K 12.4K 106
Rate this:
Please Sign up or sign in to vote.
This application provides functionality to Shutdown, Restart, Stand By, Hibernate or Log Off supported computers at a selected date and time.

Sample Image - TimerComputerShutdown.jpg

Introduction

Timer Computer Shutdown application provides functionality to shutdown, restart, stand by, hibernate or log off supported computers, at a selected date and time that has yet to elapse. Functionality of the shutdown modes has been provided by a WindowsController.cs class from http://www.mentalis.org/soft/class.qpx?id=7

WARNING: The "Brute" option will force termination of all running processes, any unsaved data will be lost; guaranteeing a shutdown. This option has been designed to close applications which produce a prompt upon closing.

The code

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 Org.Mentalis.Utilities;

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 buttonAbout; 
        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()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code 
            // after InitializeComponent call
            //
        }

        /// <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()
        {
                    ...
        }
        #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:
                    Org.Mentalis.Utilities.
                            WindowsController.ExitWindows
                            (RestartOptions.PowerOff, false);
                    break;
                case 1:
                    Org.Mentalis.Utilities.WindowsController.
                         ExitWindows(RestartOptions.Reboot, false);
                    break;
                case 2:
                    Org.Mentalis.Utilities.WindowsController.
                         ExitWindows(RestartOptions.Suspend, false);
                    break;
                case 3:
                    Org.Mentalis.Utilities.WindowsController.
                         ExitWindows(RestartOptions.Hibernate, false);
                    break;
                case 4:
                    Org.Mentalis.Utilities.WindowsController.
                         ExitWindows(RestartOptions.LogOff, false);
                    break;
            }
        }
        
        private void comboBox_SelectedIndexChanged
                 (object sender, System.EventArgs e)
        {
            this.labelSelectDateTimeToShutdownComputer.Text =
                 "Select Date/Time to" + " " + 
                 this.comboBox.SelectedItem.ToString() + 
                 " " + "computer:";
            this.labelDateTimeShutdown.Text = "Date/Time" + 
                 " " + this.comboBox.SelectedItem.ToString() + ":";
        }

        private void checkBox_CheckedChanged(object sender, 
                                        System.EventArgs e)
        {
            if (this.checkBox.Checked)
            {
                Warning warning = new Warning();
                warning.ShowDialog();
            }
        }

        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 buttonAbout_Click(object sender, 
                                    System.EventArgs e)
        {
            About about = new About();

            about.ShowDialog();
        }

        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;
            }
        }
    }
}

That's all!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Steve Puri
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralI Have Problem Pin
Ahmed Hassany10-Dec-08 3:33
memberAhmed Hassany10-Dec-08 3:33 
AnswerRe: I Have Problem Pin
monstale11-Jan-09 11:19
membermonstale11-Jan-09 11:19 
QuestionHow can run the C# program whitout .NET Framework [modified] Pin
iori10721-Oct-08 9:18
memberiori10721-Oct-08 9:18 
Questionwindows process(help me!!!)? Pin
wita23-Apr-08 16:46
memberwita23-Apr-08 16:46 
AnswerRe: windows process(help me!!!)? Pin
monstale11-Jan-09 11:24
membermonstale11-Jan-09 11:24 
QuestionWhat about CPU? Pin
huseyin6-Apr-06 21:53
memberhuseyin6-Apr-06 21:53 
AnswerRe: What about CPU? Pin
mcklain17-Dec-07 4:36
membermcklain17-Dec-07 4:36 
GeneralRe: What about CPU? Pin
Alsa7erOnline29-Apr-08 3:31
memberAlsa7erOnline29-Apr-08 3:31 
GeneralNot real smart Pin
stanleystronghold4-Mar-06 3:26
memberstanleystronghold4-Mar-06 3:26 
Generalyou can add this too. ( lock computer) Pin
Samar Aarkotti14-Nov-05 8:06
memberSamar Aarkotti14-Nov-05 8:06 
GeneralAnother way to shutdown windows Pin
Alexander Lowe26-Sep-05 11:17
sussAlexander Lowe26-Sep-05 11:17 
While this may work, and it sounds like with mixed success, you can import the ExitWindows Win32 function using interop services.

Here is a free to use and modify class I wrote while researching windows shutdown methods in .Net and not finding much success: http://www.lowesoftware.com/modules.php?op=modload&name=News&file=article&sid=14&mode=thread&order=0&thold=0[^]

Hope this helps.



-- Alex

http://www.lowesoftware.com
GeneralRe: Another way to shutdown windows Pin
Alexander M. Batishchev30-Mar-07 13:04
memberAlexander M. Batishchev30-Mar-07 13:04 
Questionshutting down othr systems??? Pin
sahithya harsha20-Sep-05 1:51
membersahithya harsha20-Sep-05 1:51 
Generalwin9x Pin
pieter@jamwarehouse.com14-Sep-05 9:30
memberpieter@jamwarehouse.com14-Sep-05 9:30 
GeneralTerminate Applicaitons Pin
tatchung29-Aug-05 22:47
membertatchung29-Aug-05 22:47 
GeneralSpin Loop in Application_Thick Pin
ebret20-Aug-05 5:59
memberebret20-Aug-05 5:59 
General,Monitor standby or Off Pin
Sean Lamacraft15-Aug-05 22:23
memberSean Lamacraft15-Aug-05 22:23 
QuestionDoes it work on Win2k? Pin
bigdude12-Jul-05 10:40
memberbigdude12-Jul-05 10:40 
GeneralIt doesn't work when Computer is Locked Pin
WillStay24-Jan-05 0:10
memberWillStay24-Jan-05 0:10 
GeneralRe: It doesn't work when Computer is Locked Pin
paintmat6-Apr-06 3:49
memberpaintmat6-Apr-06 3:49 
GeneralRe: It doesn't work when Computer is Locked Pin
WillStay6-Apr-06 5:58
memberWillStay6-Apr-06 5:58 
Generalwakeup Pin
ratho11-Nov-04 7:18
memberratho11-Nov-04 7:18 
GeneralRe: wakeup Pin
Memot4-Feb-05 5:44
sussMemot4-Feb-05 5:44 
GeneralDEVCON or shutdown commands Pin
Anonymous8-Nov-04 7:51
sussAnonymous8-Nov-04 7:51 
GeneralBrute shutdown crashes XP?! Pin
Preky14-Oct-04 23:08
memberPreky14-Oct-04 23:08 
GeneralRe: Brute shutdown crashes XP?! Pin
Steve Puri16-Oct-04 9:26
memberSteve Puri16-Oct-04 9:26 
GeneralRe: Brute shutdown crashes XP?! Pin
WillStay24-Jan-05 0:00
memberWillStay24-Jan-05 0:00 
GeneralLogoff after program finishes Pin
persicom21-Apr-04 16:59
memberpersicom21-Apr-04 16:59 
GeneralRe: Logoff after program finishes Pin
Steve Puri21-Apr-04 22:24
memberSteve Puri21-Apr-04 22:24 
GeneralSave ressources Pin
mim200027-Nov-03 22:50
sussmim200027-Nov-03 22:50 
GeneralRe: Save ressources Pin
Steve Puri28-Nov-03 1:13
memberSteve Puri28-Nov-03 1:13 
GeneralRe: Save ressources Pin
Memot13-May-04 5:17
memberMemot13-May-04 5:17 
GeneralRe: Save ressources Pin
Steve Puri13-May-04 9:00
memberSteve Puri13-May-04 9:00 
GeneralRe: Save ressources Pin
Memot14-May-04 5:12
memberMemot14-May-04 5:12 
GeneralDying to shutdown Pin
louis7-Oct-02 21:19
memberlouis7-Oct-02 21:19 
GeneralRe: Dying to shutdown Pin
Anonymous8-Oct-02 11:48
sussAnonymous8-Oct-02 11:48 
GeneralRe: Dying to shutdown Pin
jkliu8-May-05 19:37
memberjkliu8-May-05 19:37 
Generallol Pin
Steve McLenithan4-Oct-02 17:45
memberSteve McLenithan4-Oct-02 17:45 
General... Pin
Steve McLenithan4-Oct-02 12:20
memberSteve McLenithan4-Oct-02 12:20 
GeneralRe: ... Pin
Steve Puri4-Oct-02 15:15
memberSteve Puri4-Oct-02 15:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150624.2 | Last Updated 3 Oct 2002
Article Copyright 2002 by Steve Puri
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid