Apologies ahead of time if I did not indent my code properly, this is my first post. So my end goal is to create a Windows Service that watches events for when a notepad.exe process is started and in response launches mspaint.exe. This is my first time working with Windows Services but I've been able to get this code to work as a Console Application and as the Windows Service while in debug mode. However, whenever I go to install it and test as a release, it installs fine and starts up with no problem but when I launch notepad.exe nothing happens.
**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
}
}
SOLVED:
Established that the Service does in fact work. The problem was that it runs as localSystem once installed which only does background services and does not have access to the visible desktop. It was launching the paint.exe in invisible mode. See link below:
https://www.reddit.com/r/csharp/comments/5a5uof/advice_managementeventwatcher_on_a_windows/