首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

WinForms 教學:Windows Service 開發全流程(從創建到安裝部署)

     編輯:關於C語言

1. 新建 Windows Service 項目

VS 中:VC# → Windows → Windows Service,命名與路徑確定。

2. 文件構成說明

  • Program.cs:入口。
  • Service1.cs:無圖形界面,系統啟動自動加載,無需用戶登錄。需安裝並註冊表註冊。

右鍵「查看代碼」見兩關鍵方法:

  • OnStart(string[] args):服務啟動執行邏輯。
  • OnStop():服務停止執行邏輯。

3. 編寫服務邏輯(記錄系統運行信息到 C:\Log.txt)

using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;

namespace WindowsService1 {
    public partial class Service1 : ServiceBase {
        int compuTime;
        public Service1() { InitializeComponent(); }

        protected override void OnStart(string[] args) {
            FileStream fs = new FileStream(@"c:\Log.Txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine("開始時間:" + DateTime.Now);
            compuTime = Environment.TickCount;
            long curTick = Environment.TickCount;
            long diff = curTick - compuTime;
            // 計算系統/應用運行時長...
            sw.WriteLine(String.Format("本計算機已運行了 {0} 小時 {1} 分 {2} 秒", ...));
            sw.WriteLine("機器名稱:" + Environment.MachineName);
            sw.WriteLine("系統版本:" + Environment.OSVersion);
            sw.WriteLine("系統路徑:" + Environment.SystemDirectory);
            sw.WriteLine("系統用戶名:" + Environment.UserName);
            sw.WriteLine("系統.Net版本:" + Environment.Version);
            sw.Flush(); fs.Close();
        }

        protected override void OnStop() {
            FileStream fs = new FileStream(@"c:\Log.Txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine("結束時間:" + DateTime.Now);
            sw.WriteLine("************************************");
            sw.Flush(); sw.Close();
        }
    }
}

4. 添加安裝程序

設計器右鍵「添加安裝程序」生成 ProjectInstaller.cs,配置:

  • serviceProcessInstaller1.Account = LocalSystem
  • serviceInstaller1.Description、DisplayName、StartType = Automatic

5. 生成項目 → 獲得 .exe

6. 安裝服務

VS 命令提示符下:

installutil "D:\...\WindowsService1.exe"

7. 啟動/驗證/停止/協載

  • 控制面板 → 管理工具 → 服務 → 找 DisplayName → 啟動/停止。
  • 查看 C:\Log.txt 驗證輸出。
  • 協載:installutil /u "路徑\WindowsService1.exe"

8. 修改服務注意事項

修改代碼前必須先停止服務,否則重新生成會提示「exe 正在使用」。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved