Windows服务的创建、安装、调试
1:新建一個WINDOWS服務項目;
2:打開自動生成的Server1的源代碼,可以在其中看到OnStart與OnStop方法,代表的是服務的啟動與關閉;
3:將事件日志中的寫日志的方法COPY到Service1類中:
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:修改OnStart與OnStop方法:
????????????? 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組件的ServiceName、DisplayName、StartType等屬性;
設置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.Timer:Tick
System.Timers.Timer:Elapsed
?
三:調試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: 生成服務項目和安裝項目,安裝包可以使用了。
?
?
?
?
?
?
轉載于:https://www.cnblogs.com/lgzslf/archive/2012/08/14/2637868.html
總結
以上是生活随笔為你收集整理的Windows服务的创建、安装、调试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css background-posit
- 下一篇: 转_读取外部数据