闲着没事写个定时关机器

前几天在网上看到一款定时关机器,忽然想起去年自己一个人住老屋的时候我也写过一个这玩意,C#版的,当时还挺有成就感的,哈哈。

下面贴出源代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace CMDProject
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnAply_Click(object sender, EventArgs e)
        {
            int hour = Convert.ToInt32(comboBox1.SelectedItem.ToString());
            int minute = Convert.ToInt32(comboBox2.SelectedItem.ToString());
            int second = Convert.ToInt32(comboBox3.SelectedItem.ToString());

            lblTime.Text = DateTime.Now.AddHours(hour).AddMinutes(minute).AddSeconds(second).ToString("yyyy-MM-dd HH:mm:ss");
            btnCancel.Enabled = true;
            btnAply.Enabled = false;
            timer1.Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 0; i <=12; i++)
            {
                comboBox1.Items.Add(i);
            }
            comboBox1.SelectedIndex = 0;

            for (int i = 0; i <= 59; i++)
            {
                comboBox2.Items.Add(i);
            }
            comboBox2.SelectedIndex = 0;

            for (int i = 0; i <= 59; i++)
            {
                comboBox3.Items.Add(i);
            }
            comboBox3.SelectedIndex = 0;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            btnCancel.Enabled = false;
            btnAply.Enabled = true;
            timer1.Stop();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string method = string.Empty;
            if (radioButton1.Checked)
            {
                method = "-s";
            }
            else if (radioButton2.Checked)
            {
                method = "-r";
            }

            if (DateTime.Now>=Convert.ToDateTime(lblTime.Text.Trim()))
            {
                timer1.Stop();
                Process process = new Process();
                process.StartInfo.FileName = "shutdown.exe";
                process.StartInfo.UseShellExecute = false;// 不使用Shell来执行,用程序来执行
                process.StartInfo.CreateNoWindow = true; // 执行时不创建新窗口
                process.StartInfo.Arguments = string.Format("{0} -t 0", method);
                process.Start();

                //process.StandardInput.WriteLine("shutdown "+method+" -t 0");
            }
        }
    }
}

 

估计很多技术达人可能很不稀罕这个,或者有人要说我炫耀了,其实我真的没这个意思,我只是学习当中随便写点东西练手,然后出成果了之后的一种小开心,所以请大家多多海涵吧。
最后上张运行效果图:

posted @ 2011-11-28 21:54  大张三  阅读(183)  评论(0)    收藏  举报