Visual Studio → 新增專案 → Windows 服務(舊稱 NT 服務) → 命名專案(如 mcWinService)。
專案自動產生 Service1.cs(繼承 ServiceBase)。設定 ServiceName 屬性(或在建構子 this.ServiceName = "mcWinService"),便於識別。
覆寫兩個核心方法:
protected override void OnStart(string[] args) {
// 服務啟動時執行:寫入日誌、啟動執行緒、開啟連接埠等
File.AppendAllText(@"C:\temp\service.log", "Service Started: " + DateTime.Now);
}
protected override void OnStop() {
// 服務停止時執行:釋放資源、關閉連線、寫入日誌
File.AppendAllText(@"C:\temp\service.log", "Service Stopped: " + DateTime.Now);
}
建置產生 mcWinService.exe。以系統管理員身分開啟「開發人員命令提示字元」:
REM 安裝
installutil C:\mcWinService\bin\Debug\mcWinService.exe
REM 解除安裝
installutil /u C:\mcWinService\bin\Debug\mcWinService.exe
installutil.exe 會讀取專案中的 ProjectInstaller 類別(含 ServiceProcessInstaller 與 ServiceInstaller),向 SCM 註冊服務。
services.msc 或「電腦管理」→「服務」mcWinService,右鍵可「啟動」、「停止」、「暫停」、「繼續」查看 C:\temp\service.log 確認啟動/停止記錄。實際專案中建議使用 EventLog 寫入 Windows 事件記錄檔,而非純文字檔。
ServiceProcessInstaller.Account 可設為:
LocalSystem:最高權限,無網路存取權LocalService:低權限,匿名網路存取NetworkService:低權限,電腦身分網路存取User:指定使用者帳號(需密碼)// 在 Program.cs Main 中加入條件編譯,支援直接以 Console 執行偵錯
#if DEBUG
if (Environment.UserInteractive) {
var svc = new mcWinService();
svc.OnStart(null);
Console.WriteLine("Press any key to stop...");
Console.ReadKey();
svc.OnStop();
return;
}
#endif
ServiceBase.Run(new mcWinService());
protected override void OnCustomCommand(int command) {
// command 128-255 為使用者自訂
if (command == 130) ReloadConfiguration();
}
透過 sc control mcWinService 130 觸發。