繁体   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