简体   繁体   中英

.Net Detecting Application Launch

I am currently trying to monitor applications being launched and closed, below is my current code but whenever it is executed i receive an access denied error, any in depth ideas or reasons to why this is happening would be much appreciated

    class Program
        {
            static void Main(string[] args)
            {
                ManagementScope scope = new ManagementScope("root\\CIMV2");
                scope.Options.EnablePrivileges = true;
                try
                    {
                        ManagementEventWatcher startWatch = new ManagementEventWatcher(
                            new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
                        startWatch.EventArrived += new EventArrivedEventHandler(startWatch_EventArrived);
                        startWatch.Start();
                        ManagementEventWatcher stopWatch = new ManagementEventWatcher(
                        new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
                        stopWatch.EventArrived += new EventArrivedEventHandler(stopWatch_EventArrived);
                        stopWatch.Start();
                        Console.WriteLine("Press any key to exit");
                        while (!Console.KeyAvailable) System.Threading.Thread.Sleep(50);
                        startWatch.Stop();
                        stopWatch.Stop();
                    }
                catch (ManagementException e)
                    {
                        Console.WriteLine(e);
                        Console.ReadKey();
                    }
            }
            static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e) 
{
        Console.WriteLine("Process stopped: {0}", e.NewEvent.Properties["ProcessName"].Value);
      }

      static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) 
{
        Console.WriteLine("Process started: {0}", e.NewEvent.Properties["ProcessName"].Value);
      }
            }

Probably this error is occurring because you not running your application in elevated mode. If you are running your application from Visual Studio then, run Visual Studio in elevated mode, else run your application exe in elevated mode:

Right click on VS exe/shortcut and select "Run as Administrator" option.

If you are directly running your application exe, then right click on your application exe and select "Run as Administrator"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM