Windows服务上的ManagementEventWatcher在调试时工作,但在安装时不起作用

本文关键字:工作 不起作用 安装 调试 服务 ManagementEventWatcher Windows | 更新日期: 2023-09-27 18:15:26

如果我没有正确缩进我的代码,请提前道歉,这是我的第一篇文章。因此,我的最终目标是创建一个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 
}
}

Windows服务上的ManagementEventWatcher在调试时工作,但在安装时不起作用

SOLVED:

确定服务确实工作。问题是,一旦安装,它作为localSystem运行,只做后台服务,不能访问可见的桌面。它以不可见模式启动paint.exe。请看下面的链接:

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

相关文章: