最近寫了一個小程式,在遠程伺服器上運行,可是在系統登出當前登陸使用者時,使用者啟動的程式也停止了,查了很多資料,也嘗試修改註冊表等,都不理想,乾脆不偷懶了,老老實實寫成windows服務吧;建立一個簡單的windows服務的步驟如下:
(1).建立一個windows服務工程,在設計頁面上點右鍵,出現菜單後,選擇添加安裝程式。這時會出現一個新的頁面,頁面上有個控制項 serviceProcessInstaller1和serviceInstaller1,在 serviceProcessInstaller1中把屬性Account改為LocalSystem,再把serviceInstaller1中把屬性Parent 改為serviceProcessInstaller1 ,ServiceName屬性是產生服務後的服務名字(假如為Msg).
(2).把這個控制項的屬性改完以後。回到建立的服務頁的後台,添加自己的代碼:
(3).代碼書寫完成後,產生一下,找到工程目錄下剛產生的exe檔案,把這個檔案複製到f盤.在運行輸入cmd,進入以下目錄:cd C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727,安裝此服務:installutil f:/ServiceTest.exe.(卸載服務的方法為:installutil f:/ServiceTest.exe-u).
(4).服務安裝完成後,啟動服務 net start msg,(msg為服務名稱),這樣一個簡單的服務就完成了.附代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace MsgService
...{
/**//// <summary>
/// Explain: Windows服務
/// Author:YMQ
/// CreateDate:2008-04-02
/// Last Modify:
/// </summary>
public partial class Service1 : ServiceBase
...{
private System.Timers.Timer timerSender;
public Service1()
...{
InitializeComponent();
this.timerSender = new System.Timers.Timer();
this.timerSender.Interval = 120000; //2分鐘
this.timerSender.Elapsed += new System.Timers.ElapsedEventHandler(timerSender_Elapsed);
}
//服務啟動
protected override void OnStart(string[] args)
...{
try
...{
string strPath = AppDomain.CurrentDomain.BaseDirectory; //應用程式相對路徑
StreamWriter sw = new StreamWriter(@strPath + @"SendMsgLog.txt", true, System.Text.Encoding.Default);
sw.Write(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + " ");
sw.Close();
this.timerSender.Enabled = true; //啟動迴圈發送
}
catch (Exception ex)
...{
string strPathErr = AppDomain.CurrentDomain.BaseDirectory;
StreamWriter swerr = new StreamWriter(@strPathErr + @"SendMsgErr.txt", true, System.Text.Encoding.Default);
swerr.Write(ex.Message+" ");
swerr.Close();
}
}
protected override void OnStop()
...{
// TODO: 在此處添加代碼以執行停止服務所需的關閉操作。
}
//迴圈檢測發送資訊
private void timerSender_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
...{
StreamWriter sw=null;
try
...{
string strPath = AppDomain.CurrentDomain.BaseDirectory; //應用程式相對路徑
sw = new StreamWriter(@strPath + @"SendMsgLog.txt", true, System.Text.Encoding.Default);
sw.Write(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + " 啟動: ");
}
catch (Exception ex)
...{
string strPathErr = AppDomain.CurrentDomain.BaseDirectory; //應用程式相對路徑
StreamWriter swErr = new StreamWriter(@strPathErr + @"SendMsgErr.txt");
swErr.Write(ex.Message+" ");
swErr.Close();
}
finally
...{
sw.Close();
}
}
}
}