Windows服务的创建、安装、调试

来源:互联网 发布:郴州干部网络培训 编辑:程序博客网 时间:2024/05/06 20:39

1:新建一个WINDOWS服务项目;

2:打开自动生成的Server1的源代码,可以在其中看到OnStartOnStop方法,代表的是服务的启动与关闭;

3:将事件日志中的写日志的方法COPYService1类中:

public void WriteLog(string logName, string SourceName, string LogText, EventLogEntryType type)

        {

            // Create an EventLog instance and assign its source.

            EventLog el = new EventLog();

            try

            {

                // Create the source, if it does not already exist.

                if (!EventLog.SourceExists(SourceName))

                {

                    if (EventLog.Exists(logName))

                    {

                        el.Log = logName;

                    }

                    else

                    {

                        EventLog.CreateEventSource(SourceName, logName);

                    }

                }

                el.Source = SourceName;

                el.WriteEntry(LogText, type);

            }

            catch (Exception ex)

            {

                el.WriteEntry(ex.Message, EventLogEntryType.Error);

            }

        }

4:修改OnStartOnStop方法:

              protected override void OnStart(string[] args)

        {

            WriteLog("Lgz12813Log""Lgz12813Src""test start..."EventLogEntryType.Information);

        }

 

        protected override void OnStop()

        {

            WriteLog("Lgz12813Log""Lgz12813Src""test stop..."EventLogEntryType.Information);

        }

5:在Services1的设计视图的右键菜单中选择“添加安装程序”;

切换到刚被添加的ProjectInstaller的设计视图,可以设置serviceInstaller1组件的ServiceNameDisplayNameStartType等属性;

设置serviceProcessInstaller1组件的Account属性的值为 LocalSystem

6:生成解决方案;

7:打开VS自带的CMD窗口,切换到项目的bin\Debug路径下,这里有编译生成的exe文件;

8:执行安装服务的命令:installutil *****.exe 

9:安装完成后,可以到管理工具\服务中找到安装好的服务,如未启动,可以将其启动;然后再将服务停止;

10:此时可以到事件查看器中查看日志记录;

11:卸载服务:installutil /u *****.exe 

最基本的使用方法到此结束。

 

其他:

一: Windows服务中使用MessageBox弹出框

1:添加对System.Windows.Forms的引用;

2:使用6个参数的重载形式:MessageBox.Show(""""MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);

 

二: Windows服务中使用Timer组件

不管从工具箱中什么地方(包括从组件中)拖进来的Timer都是System.Windows.Forms.Timer(网上说是WS的一个BUG,在Windows服务中需要使用System.Timers.Timer,我的办法是从工具箱中拖进来之后,到.Designer.cs文件中修改实例化的代码。

注意:两个Timer组件的到期事件名不一样:

System.Windows.Forms.TimerTick

System.Timers.TimerElapsed

 

三:调试Windows服务

方法一:使用 MessageBox.Show 显示出想要查看的信息;

方法二:将服务安装且启动后,使用 “附加到进程” 的方法;

参见:http://www.cnblogs.com/xiaoxiangfeizi/archive/2012/04/18/2454715.html

 

四:安装Windows服务

前面提到过使用installutil.exe文件安装windows 服务,使用安装包安装将更简单。 

1:在解决方案中添加一个“安装项目”:选中解决方案-右键-添加-新建项目-其他项目类型-安装和部署-Visual Studio Installer-安装项目

2:应用程序文件夹-添加-项目输出- 在项目中选择你的Windows Service项目-主输出-确定

3:选中安装项目-右键-视图-自定义操作-安装-添加自定义操作- 应用程序文件夹 - 主输出;在卸载中也添加主输出;

4: 生成服务项目和安装项目,安装包可以使用了。

原创粉丝点击