码迷,mamicode.com
首页 > Windows程序 > 详细

C#创建Windows服务

时间:2018-03-16 17:21:21      阅读:425      评论:0      收藏:0      [点我收藏+]

标签:post   com   cep   thread   计算机   partial   res   服务控制   mode   

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
 
namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
 
        protected override void OnStart(string[] args)
        {
            try
            {
                EventLog.WriteEntry("我的服务启动");
                WriteLog("服务启动");
                Timer t = new Timer();
                t.Interval = 1000;
                t.Elapsed += new ElapsedEventHandler(ChkSvr);
                t.AutoReset = true;
                t.Enabled = true;
 
            }
 
            catch (System.Exception ex)
            {
 
                //错误处理  
 
            }
        }
        public void ChkSvr(object source, ElapsedEventArgs e)
        {
            try
            {
                Timer tt = (Timer)source;
                tt.Enabled = false;
                SendMessahe();
                tt.Enabled = true;
            }
            catch (Exception ex)
            {
 
                WriteLog(ex.Message);
            }
        }
        public void SendMessahe()
        {
            try
            {
                WriteLog("这里是要执行的任务");
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
            }
        }
        public void WriteLog(string read)
        {
            System.IO.StreamWriter sw = new System.IO.StreamWriter(@"c:/" + "ceshi.text", true);
            sw.Write("\r\n事件:" + read + "\r\n操作时间:" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "");
            sw.Close();
        }
        protected override void OnStop()
        {
            WriteLog("服务停止");
            EventLog.WriteEntry("我的服务停止");
        }
    }
}
在安装程序中选中【serviceProcessInstaller1】,查看其属性,将【Account】值改为【LocalSystem】。
在安装程序中选中【serviceInstaller1】,查看其属性,将【ServiceName】值改为你想要的服务名称。 在目录【C:\Windows\Microsoft.NET\Framework】中找到程序对应的.net版本 找到【InstallUtil.exe】 复制到 项目 bin/debug 下
无法打开计算机“.”上的服务控制管理器。此操作可能需要其他特权。:使用管理员权限打开cmd

C#创建Windows服务

标签:post   com   cep   thread   计算机   partial   res   服务控制   mode   

原文地址:https://www.cnblogs.com/otsf/p/8582354.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!