利用VC#.NET 2005 的Windows服务项目创建一个Windows服务

 

利用VC#.NET 2005 的Windows服务项目创建一个Windows服务。功能:每一小时提示一个对话框!

#主程式 Program.cs

using System.Collections.Generic;
using System.ServiceProcess;
using System.Text;
using System;

namespace TimeForAction
{
    static class Program
    {

        //将有SCM System Control Manager来调用 
        static void Main(string[] args)         {         
               ServiceBase.Run(new TimeForAction());
     }
    }
}

//TimeForAction.cs 实现类

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

namespace TimeForAction
{
    public partial class TimeForAction : ServiceBase
    {
        private Thread MyThread;

        public TimeForAction()
        {
            InitializeComponent();

            MyThread = new Thread(new ThreadStart(ThreadFunc));

            MyThread.Priority = ThreadPriority.Lowest;
        }

        protected override void OnStart(string[] args) //实现ServiceBase的接口
        {
            MyThread.Start();
        }

        protected override void OnStop()  //实现ServiceBase的接口
        {
            MyThread.Abort();
        }

        private void ThreadFunc()  //线程入口函数

         {

            int LastHour = DateTime.Now.Hour;

            while (true)
            {
                System.Threading.Thread.Sleep(60000);

                if (DateTime.Now.Hour - 1 == LastHour)
                {
                    MessageBox.Show("为了您的身体,请起来动动休息5分钟!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);

                    LastHour = DateTime.Now.Hour;

                }
            }
          }

    }
}


//TimeForAction.Designer.cs //界面设计

TimeForActionnamespace TimeForAction
{
    partial class TimeForAction
    {
 
        private System.ComponentModel.IContainer components = null;
       
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

   
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.ServiceName = "TimeForAction";
        }
       

    }
}
最后编译并生成。不能直接运行。必须先安装为windows 服务。 在设计页面上点右键,出现菜单后,选择添加安装程序。这时会出现一个新的页面,页面上有控件 serviceProcessInstaller1和serviceInstaller1 ,在 serviceProcessInstaller1中把属性Account改为LocalSystem,在把serviceInstaller1中把属性Parent 改为serviceProcessInstaller1 完成之后编译并生成,假设生成cjb.exe 那么进入WINDOWS\Microsoft.NET\Framework\v2.0.50727
InstallUtil cjb.exe        安装服务
InstallUtil cjb.exe -u    卸载服务

最后就可以看到系统服务选项就有你安装的服务了。

posted on 2011-01-07 16:02  努力实现目标  阅读(615)  评论(0编辑  收藏  举报