Service1.cs(設計介面)與 Program.cs(進入點)。using System; using System.ServiceProcess; using System.Threading; using System.Windows.Forms;
namespace CareEye {
public partial class CareEye : ServiceBase {
Thread _mainThread;
public CareEye() {
InitializeComponent();
_mainThread = new Thread(ThreadFunc) { Priority = ThreadPriority.Lowest };
}
static void Main() {
ServiceBase.Run(new CareEye());
}
protected override void OnStart(string[] args) {
_mainThread.Start(); // 啟動背景執行緒
}
protected override void OnStop() {
_mainThread.Abort(); // 停止執行緒
}
void ThreadFunc() {
int lastHour = DateTime.Now.Hour;
while (true) {
Thread.Sleep(60000); // 每分鐘檢查
if (DateTime.Now.Hour - 1 == lastHour) {
MessageBox.Show("為了愛護您的眼睛,請暫時休息5分鐘並向遠處眺望!",
"警告", MessageBoxButtons.OK, MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
lastHour = DateTime.Now.Hour;
}
}
}
}
}
Service1.cs 設計介面右鍵 → 加入安裝程式。ProjectInstaller.cs,包含 serviceProcessInstaller1 與 serviceInstaller1。serviceProcessInstaller1.Account = LocalSystem(或 User/NetworkService)。serviceInstaller1.Parent = serviceProcessInstaller1。serviceInstaller1.ServiceName = 服務顯示名稱(如 "CareEye")。bin\Release\CareEye.exe。F:\CareEye.exe)。cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 (依安裝版本調整)
installutil F:\CareEye.exe // 安裝服務
installutil /u F:\CareEye.exe // 移除服務
services.msc → 找到 "CareEye" → 右鍵 啟動。net start CareEye / net stop CareEye。MessageBox.Show 加上 MessageBoxOptions.DefaultDesktopOnly 僅供測試,正式環境請改用事件日誌(EventLog)記錄。Thread.Abort() 不推薦用於生產環境,建議使用 CancellationToken 或旗標讓執行緒自行結束。installutil 失敗。ServiceName) 需唯一,不可與現有服務重複。// 在 OnStart 加入
#if DEBUG
System.Diagnostics.Debugger.Launch(); // 啟動時自動附加偵錯器
#endif
或將服務邏輯抽離為獨立類別,以 Console Application 執行測試,再移植回服務。