簡體   English   中英

Windows Service上的ManagementEventWatcher可在調試中工作,但不能在安裝時工作

[英]ManagementEventWatcher on a Windows Service works in debug but not on install

如果我沒有正確縮進代碼,請提前道歉,這是我的第一篇文章。 因此,我的最終目標是創建一個Windows服務,以監視notepad.exe進程何時啟動以及相應地啟動mspaint.exe的事件。 這是我第一次使用Windows服務,但是我已經能夠在調試模式下將此代碼用作控制台應用程序和Windows服務。 但是,每當我去安裝它並作為發行版進行測試時,它都可以很好地安裝並且可以毫無問題地啟動,但是當我啟動notepad.exe時,什么也沒有發生。

**MyNewService.cs**
public MyNewService()
{
InitializeComponent();
System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory +"Initialized.txt");
}
public void OnDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Start();
}
protected override void OnStop()
{
System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "OnStop.txt");
}

static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
string instanceName = ((ManagementBaseObject)e.NewEvent["TargetInstance"])["Name"].ToString();
if (instanceName.ToLower() == "notepad.exe")
{
Process.Start("mspaint.exe");
}
}
}
**Main Program**
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
#if DEBUG
MyNewService myService = new MyNewService();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyNewService()
};
ServiceBase.Run(ServicesToRun);
#endif 
}
}

解決了:

確定該服務確實有效。 問題在於,它一旦安裝便以localSystem的形式運行,它僅提供后台服務,而無權訪問可見的桌面。 它以不可見模式啟動paint.exe。 請參閱下面的鏈接:

https://www.reddit.com/r/csharp/comments/5a5uof/advice_managementeventwatcher_on_a_windows/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM