单位内有600 700台电脑,每天下班后有大量的空闲电脑处于开机状态,这导致大量电力资源的浪费。

针对上述问题,设计了一个小程序,有以下3个功能;

1、每天定时启动倒计时。

2、倒计时30秒,若无人操作,则关机;若有人操作,则可以取消关机。

3、其余时间程序在后台运行,不在任务栏显示。

 

在程序中,本人使用了2个Timer控件。一个用来监视电脑本地的时间(GlbTimer),另一个用来倒计时30秒(CountdownTimer)。

Timer控件中有个Interval属性,用来设定Timer控件的时间间隔。

Timer控件中有个Tick事件,在该事件中编写每个时间间隔所要执行的代码。

 

先贴上GlbTimer的Tick事件代码:



private void GlbTime_Tick(object sender, EventArgs e)
        {
            if (DateTime.Now.Hour.ToString() == "17")//获取系统时间 当小时等于17时 
            {
                CountdownTimer.Enabled = true;//CountdownTimer是倒计时30秒的Timer控件
                this.Visible = true;//将窗口设置成可见
                this.TopMost = true;//讲窗口置于最前
            }
        }



再贴上CountdownTimer的Tick事件代码:



private void CountdownTimer_Tick(object sender, EventArgs e)
        {
            
            DateTime dt = DateTime.Now;
            lblSHowTime.Text = dt.ToString();//获取系统时间 然后在lblShowTime中显示

            if (time == 0)//time在类中定义为 private int time = 30 表示30秒倒计时
            {
                shutdownComputer();//执行关机操作
            }
            else
            {
                time = time - 1;
                lblTime.Text = time.ToString();//将倒计时所剩下的时间显示在lbltime中显示
            }
        }



然后是关于shutdownComputer()这个方法的实现。实质就是通过程序调用cmd的shutdown方法。代码如下:



public void shutdownComputer()
        {
            Process myProcess = new Process();
            myProcess.StartInfo.FileName = "cmd.exe";
            myProcess.StartInfo.UseShellExecute = false;
            myProcess.StartInfo.RedirectStandardInput = true;
            myProcess.StartInfo.RedirectStandardOutput = true;
            myProcess.StartInfo.RedirectStandardError = true;
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.Start(); myProcess.StandardInput.WriteLine("shutdown -s -t 0");
        }



然后要使程序在后台运行。在窗口中有个Actived事件,每当窗口处于激活、活动状态时就会触发代码。



private void MainFrm_Activated(object sender, EventArgs e)
        {
            this.Hide();
            this.Activated -= MainFrm_Activated;
        }



执行了一次代码,使窗口隐藏,然后在隐藏之后将这个动作删除。若不删除,当窗口显示出来时,又会调用此Activated事件,继续将窗口隐藏。(上文GlbTimer的Tick事件会触发Actived事件)

 

取消关机代码,很简单,直接退出程序即可。



private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }



 

最后将程序拖入开机启动项中。这样,程序每天都会在开机时在后台运行起来,到了每天的下午5点,就弹出form,然后倒计时30秒。若无人操作则关机,若电脑有人操作,就可以手动取消关机。

ps:此程序需要.net 2.0的框架。