您的位置:首页 > 编程语言 > C#

C#编写windows服务

2010-04-17 15:08 169 查看
windows服务大家都知道,就是这些东东。如下



打开VS2008,新建一个windows服务项目。切换到设计视图,拖一个timer控件上去。如下



ok,设置timer的Enable=true,interval=1000。双击timer控件,写如下代码
private void timer1_Tick(object sender, EventArgs e)
{
if (DateTime.Now.ToShortTimeString().CompareTo(DateTime.Parse("23:00:00")) > 0)
{
System.Diagnostics.Process pro = new Process();
pro.StartInfo.FileName = "cmd.exe";
pro.StartInfo.UseShellExecute = true;
pro.StartInfo.RedirectStandardInput = true;
pro.StartInfo.RedirectStandardOutput = true;
pro.StartInfo.RedirectStandardError = true;
pro.StartInfo.CreateNoWindow = true;
pro.Start();
pro.StandardInput.WriteLine("shutdown -s -t 0");
}
}
写完之后我们在设计视图上单击右键选择“添加安装程序”,出现了两个installer。如下



我们设置serviceProcessInstaller1组件的属性Account = LocalSystem(运行此服务的账户类型为本地系统)。再设置serviceInstaller1的属性Description为“为了让老爸在11点关机”。再设置其serviceName为“shutdownComputer”,其startType为Automatic(自动启动),设置其DisplayName为“定时关机”。

ok运行
InstallUtil WindowService1.exe。注册这个服务,在C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322下有个installutil.exe,打开运行输入:C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\installutil F:\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe。其中F:\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe为你的服务所在的位置。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息