Windows 服務需顯示 UI 視窗、彈出訊息方塊或啟動 GUI 程式時,必須勾選「允許服務與桌面互動」。透過 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);
EnableDesktopInteraction();
}
private void EnableDesktopInteraction()
{
try
{
var options = new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate };
var scope = new ManagementScope(@"root\CIMV2", options);
scope.Connect();
// 服務名稱需與 serviceInstaller1.ServiceName 一致
string serviceName = "MyCustomService";
var service = new ManagementObject($"Win32_Service.Name='{serviceName}'");
var inParams = service.GetMethodParameters("Change");
inParams["DesktopInteract"] = true;
service.InvokeMethod("Change", inParams, null);
}
catch (Exception ex)
{
// 記錄日誌,不要拋出以免安裝失敗
System.Diagnostics.EventLog.WriteEntry("MyServiceInstaller",
$"啟用桌面互動失敗: {ex.Message}", EventLogEntryType.Warning);
}
}
}
ServiceInstaller.ServiceName 完全一致,區分大小寫。OnCommitted 確保服務已建立於 SCM 中。