好长时间没写代码了,前几天闲着没事的时候写了一个定时关机器,真的挺有成就感的,哈哈。
编译过的程序已经传到网上,大家可以下载试试玩。
http://www.enmay.com/thread-1019-1-1.html
下 面贴出源代码:
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();
}
}
}
}
最后上张运行效果图: