Windows 服務預設在 Session 0 隔離執行,無法直接顯示 UI 或與使用者桌面互動。若舊版服務需顯示視窗 (不建議新架構使用),可在安裝程式 `ProjectInstaller` 的 `OnCommitted` 事件中透過 WMI 修改服務屬性啟用「允許服務與桌面互動」。
using System;
using System.Collections;
using System.Management;
using System.ServiceProcess;
[RunInstaller(true)]
public partial class ProjectInstaller : Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
protected override void OnCommitted(IDictionary savedState)
{
base.OnCommitted(savedState);
EnableDesktopInteract();
}
private void EnableDesktopInteract()
{
try
{
// 連接本機 WMI
var options = new ConnectionOptions
{
Impersonation = ImpersonationLevel.Impersonate
};
var scope = new ManagementScope(@"root\CIMV2", options);
scope.Connect();
// 取得服務物件 (服務名稱需與 serviceInstaller1.ServiceName 一致)
string serviceName = "MyCustomService"; // 替換為實際服務名稱
var wmiService = new ManagementObject($"Win32_Service.Name='{serviceName}'");
// 呼叫 Change 方法修改 DesktopInteract 屬性
var inParams = wmiService.GetMethodParameters("Change");
inParams["DesktopInteract"] = true; // 關鍵:啟用桌面互動
var outParams = wmiService.InvokeMethod("Change", inParams, null);
uint result = (uint)outParams["ReturnValue"];
if (result != 0)
{
// 記錄錯誤:常見 2=存取被拒(需管理員)、3=參數錯誤
System.Diagnostics.EventLog.WriteEntry("MyServiceInstaller",
$"啟用桌面互動失敗,WMI 回傳碼: {result}",
System.Diagnostics.EventLogEntryType.Error);
}
}
catch (Exception ex)
{
System.Diagnostics.EventLog.WriteEntry("MyServiceInstaller",
$"設定桌面互動異常: {ex.Message}",
System.Diagnostics.EventLogEntryType.Error);
}
}
}
| 項目 | 說明 |
|---|---|
| 適用版本 | Windows XP / Server 2003 至 Windows 10 / Server 2019 (Session 0 隔離機制下仍可設定,但行為受限) |
| Session 0 隔離 | Vista 之後服務運行於 Session 0,使用者桌面為 Session 1+,啟用此選項服務建立的視窗會顯示在「互動式服務偵測」視窗中,而非直接顯示 |
| 權限需求 | 安裝程式必須以**系統管理員身分執行** (UAC 昇權),否則 WMI Change 會回傳存取被拒 (代碼 2) |
| 服務名稱 | 必須與 `ServiceInstaller.ServiceName` 完全一致 (非 DisplayName) |
| 現代替代方案 | 強烈不建議新專案使用此模式。改用: • 獨立 GUI 應用程式 + 服務透過 IPC (Named Pipe/TCP/共享記憶體) 通訊 • 系統托盤應用程式監控服務狀態 • Web 管理介面 (ASP.NET Core + SignalR) |
inParams["DesktopInteract"] = false; // 設為 false 即可關閉
僅在維護極舊版 Win32 服務且無法重構時使用此技術,新開發請採用「服務 + 獨立前端」架構分離關注點。