如果我没有正确缩进我的代码,请提前道歉,这是我的第一篇文章。因此,我的最终目标是创建一个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
}
}
答案 0 :(得分:0)
解决:
确定该服务确实有效。问题是它一旦安装就运行为localSystem,它只执行后台服务并且无法访问可见桌面。它以无形模式启动paint.exe。请参阅以下链接:
https://www.reddit.com/r/csharp/comments/5a5uof/advice_managementeventwatcher_on_a_windows/