public void AddWatcher(string source, string log, int id) { if (source == log && log == null) { throw new ArgumentNullException("Either source or log must be set!"); } // if legeacy if (System.Environment.OSVersion.Version.Major < 6) { string queryString = "Select * from __InstanceCreationEvent Where TargetInstance ISA 'Win32_NTLogEvent'"; if (source != null) queryString += " AND TargetInstance.Sourcename = '" + source + "'"; if (log != null) queryString += " AND TargetInstance.LogFile = '" + log + "'"; queryString += " AND (TargetInstance.EventCode = " + id + ")"; ManagementEventWatcher managementWatcher = new ManagementEventWatcher(new EventQuery(queryString)); managementWatcher.Start(); managementWatcher.EventArrived += EventRecordWritten; managementWatchers.Add(managementWatcher); } else { string queryString = "<QueryList><Query Id='0' Path='" + log + "'><Select Path='" + log + "'>*[System[Provider[@Name='" + source + "']]] and *[System[EventID=" + id + "]]</Select></Query></QueryList>"; EventLogQuery query = new EventLogQuery(log, PathType.LogName, queryString); EventLogWatcher eventWatcher = new EventLogWatcher(query); eventWatcher.EventRecordWritten += EventRecordWritten; eventWatcher.Enabled = true; eventWatchers.Add(eventWatcher); } }
/// <summary> /// Initializes a new instance of the <see cref="Program"/> class. /// </summary> public Program() { try { // Your query goes below; "KeyPath" is the key in the registry that you // want to monitor for changes. Make sure you escape the \ character. WqlEventQuery query = new WqlEventQuery( "SELECT * FROM RegistryValueChangeEvent WHERE " + "Hive = 'HKEY_LOCAL_MACHINE'" + @"AND KeyPath = 'SOFTWARE\\Microsoft\\.NETFramework' AND ValueName='InstallRoot'"); ManagementEventWatcher watcher = new ManagementEventWatcher(query); Console.WriteLine("Waiting for an event..."); // Set up the delegate that will handle the change event. watcher.EventArrived += new EventArrivedEventHandler(HandleEvent); // Start listening for events. watcher.Start(); // Do something while waiting for events. In your application, // this would just be continuing business as usual. System.Threading.Thread.Sleep(100000000); // Stop listening for events. watcher.Stop(); } catch (ManagementException managementException) { Console.WriteLine("An error occurred: " + managementException.Message); } }
public static ManagementEventWatcher RegisterRemoveEvent(UsbEvent RemoveEvent) { var removeQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3"); var removeWatcher = new ManagementEventWatcher(removeQuery); removeWatcher.EventArrived += delegate(object sender, EventArrivedEventArgs e) { // string driveName = e.NewEvent.Properties["DriveName"].Value.ToString(); Action action = delegate { RemoveEvent(); }; Application.Current.Dispatcher.BeginInvoke(action); }; removeWatcher.Start(); return(removeWatcher); }
public void Dispose() { if ((this._ProcessInstance != null)) { this._ProcessInstance.EnableRaisingEvents = false; this._ProcessInstance.Close(); } this._ProcessInstance = null; if ((this.processStartEvent != null)) { this.processStartEvent.Stop(); this.processStartEvent.Dispose(); } this.processStartEvent = null; }
private void MonitorDeviceChanges() { var deviceArrivalQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"); var deviceRemovalQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3"); arrival = new ManagementEventWatcher(deviceArrivalQuery); removal = new ManagementEventWatcher(deviceRemovalQuery); arrival.EventArrived += (o, args) => RaisePortsChangedIfNecessary(EventType.Insertion); removal.EventArrived += (sender, eventArgs) => RaisePortsChangedIfNecessary(EventType.Removal); // Start listening for events arrival.Start(); removal.Start(); }
private void DoWork(object sender, DoWorkEventArgs e) { WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_Volume' AND ( TargetInstance.DriveType=2 OR TargetInstance.DriveType=3 ) AND TargetInstance.FileSystem='NTFS'"); ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery); insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent); insertWatcher.Start(); WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_Volume' AND ( TargetInstance.DriveType=2 OR TargetInstance.DriveType=3 ) AND TargetInstance.FileSystem='NTFS'"); ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery); removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent); removeWatcher.Start(); }
private void backgroundWorker1_DoWork() { WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'"); ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery); insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent); insertWatcher.Start(); WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'"); ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery); removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent); removeWatcher.Start(); }
public MainForm() { InitializeComponent(); string query = "SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance isa \"WIN32_SerialPort\""; ManagementEventWatcher watcher = new ManagementEventWatcher(query); watcher.EventArrived += Watcher_SerialPortCreation; watcher.Start(); query = "SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance isa \"WIN32_SerialPort\""; watcher = new ManagementEventWatcher(query); watcher.EventArrived += Watcher_SerialPortDeletion; watcher.Start(); }
public WmiBrightnessController() { GetBrightness(); ManagementScope scope = new ManagementScope("root\\WMI"); EventQuery q = new EventQuery("Select * From WmiMonitorBrightnessEvent"); _eventWatcher = new ManagementEventWatcher(scope, q); _eventWatcher.EventArrived += (s, arg) => { MonitorBrightness = (byte)arg.NewEvent.Properties["Brightness"].Value; MonitorBrightnessChanged?.Invoke(this, new MonitorBrightnessChangedEventArgs(MonitorBrightness)); }; _eventWatcher.Start(); }
public static void Main() { WqlEventQuery q = new WqlEventQuery(); q.EventClassName = "__InstanceModificationEvent "; q.Condition = @"TargetInstance ISA 'Win32_LocalTime' AND TargetInstance.Hour = 22 AND TargetInstance.Minute = 7 AND TargetInstance.Second = 59"; Console.WriteLine(q.QueryString); using (ManagementEventWatcher w = new ManagementEventWatcher(q)) { w.EventArrived += new EventArrivedEventHandler(TimeEventArrived); w.Start(); Console.ReadLine(); // Block this thread for test purposes only.... w.Stop(); } }
private void FrmSelectDrive_Load(object sender, EventArgs e) { this.method_0(true); try { this.managementEventWatcher_0 = new ManagementEventWatcher(); WqlEventQuery wqlEventQuery = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 OR EventType = 3"); this.managementEventWatcher_0.EventArrived += new EventArrivedEventHandler(this.managementEventWatcher_0_EventArrived); this.managementEventWatcher_0.Query = (EventQuery)wqlEventQuery; this.managementEventWatcher_0.Start(); } catch { } }
static void Main(string[] args) { var queryString = "SELECT TargetInstance " + "FROM __InstanceCreationEvent WITHIN 1 " + "WHERE TargetInstance ISA 'Win32_Process' " + "AND TargetInstance.Name LIKE 'notepad.exe'"; var scope = @"\\.\root\CIMV2"; var watcher = new ManagementEventWatcher(scope, queryString); watcher.EventArrived += watcher_EventArrived; watcher.Start(); Process.Start("notepad.exe"); Console.ReadKey(); }
public void RemoveUSBEventWatcher() { if (this.insertWatcher != null) { this.insertWatcher.Stop(); this.insertWatcher = (ManagementEventWatcher)null; } if (this.removeWatcher == null) { return; } this.removeWatcher.Stop(); this.removeWatcher = (ManagementEventWatcher)null; }
public ProcessMonitor(string processName) { this.startWatcher = new ManagementEventWatcher($@"Select * From Win32_ProcessStartTrace WHERE ProcessName LIKE ""{processName}"""); this.stopWatcher = new ManagementEventWatcher($@"Select * From Win32_ProcessStopTrace WHERE ProcessName LIKE ""{processName}"""); var noextName = Path.GetFileNameWithoutExtension(processName); this.RunningProcesses = new ObservableCollection <ProcessItem>( Process.GetProcesses() .Where(p => p.ProcessName.Equals(noextName, StringComparison.InvariantCultureIgnoreCase) && p.MainModule != null) .DistinctBy(p => p.MainModule) .Select(p => new ProcessItem(p.Id, p.ProcessName, Path.GetDirectoryName(p.MainModule?.FileName), p.CommandLine())) ); this.Initialize(); }
/// <summary> /// Вызывается при запуске сервиса /// </summary> protected override void OnStart(string[] args) { base.OnStart(args); // Регистрируем наш обработчик событий сервиса RegisterDeviceNotification(); _db = new LogDatabase(); // Если файл не существует на диске, то просим базу данных его создать и даём администраторам доступ к файлу if (!File.Exists(_dbPath)) { _db.Database.Initialize(false); GrantAccess(_dbPath); } // Отдельный поток для сохранения базы данных каждые 5 секунд _dbSaverThread = new Thread(DbSaver); // Подписываемся на события вставки/удаления usb WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 OR EventType = 3"); _mewCreation = new ManagementEventWatcher(query); _mewCreation.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation); // Получаем список дисков, которые уже подключены при запуске сервиса var usbDisks = GetLogicalUsbDisks(); if (usbDisks == null) { Console.WriteLine("Cannot get usb disks, stopped."); Stop(); return; } // И проверяем допустимы ли они (если нет, то отключаем их) foreach (var item in usbDisks) { if (item["caption"] == null) { continue; } CheckAttachedUsb((string)item["caption"], (string)item["VolumeSerialNumber"]); } // Запускаем подписку на события и сохранялку базы данных _mewCreation.Start(); _dbSaverThread.Start(); }
/// <summary> /// Instantiates a new instance of the <see cref="ServiceWatcher"/> class. /// </summary> /// <param name="watchForServiceCreation">Flag indicating whether the watcher will monitor service creation.</param> /// <param name="watchForServiceDeletion">Flag indicating whether the watcher will monitor service deletion.</param> /// <param name="watchForServiceStatusChange">Flag indicating whether the watcher will monitor service status changes.</param> /// <param name="asynchronous">Flag indicating if the watcher uses asnynchronous or semi-synchronous operations.</param> /// <param name="isMachineOnline">Flag indicating whether the consumer machine is online.</param> public ServiceWatcher(bool watchForServiceCreation, bool watchForServiceDeletion, bool watchForServiceStatusChange, bool asynchronous, bool isMachineOnline) { _wmiAsyncCreationWatcher = null; _wmiAsyncDeletionWatcher = null; _wmiAsyncStatusChangeWatcher = null; _wmiSemiSyncCreationWatcher = null; _wmiSemiSyncDeletionWatcher = null; _wmiSemiSyncStatusChangeWatcher = null; Asynchronous = asynchronous; IsMachineOnline = isMachineOnline; IsRunning = false; WatchForServiceCreation = watchForServiceCreation; WatchForServiceDeletion = watchForServiceDeletion; WatchForServiceStatusChange = watchForServiceStatusChange; WmiQueriesTimeoutInSeconds = WMI_QUERIES_DEFAULT_TIMEOUT_IN_SECONDS; }
public StudyLockerService() { InitializeComponent(); this.eventLog1 = new System.Diagnostics.EventLog(); if (!EventLog.SourceExists("StudyLockerServiceBeta2")) { EventLog.CreateEventSource("StudyLockerServiceBeta2", "Study Locker"); } eventLog1.Source = "StudyLockerServiceBeta2"; eventLog1.Log = "Study Locker"; processStartWatch = new ManagementEventWatcher( new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace")); processStartWatch.EventArrived += ProcessStartWatch_EventArrived; processStartWatch.Start(); }
static void Main(string[] args) { /** * ManagementEventWatcher is useful to interact to Windows to get the event of plugged usb * */ ManagementEventWatcher watcher = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2"); while (true) { watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Query = query; watcher.Start(); watcher.WaitForNextEvent(); } }
private void Stop() { if (m_watcher != null) { try { m_watcher.Stop(); m_watcher.EventArrived -= new System.Management.EventArrivedEventHandler(EventArrived); m_watcher = null; } catch { //throw new Exception(); } } }
private void WatchForProcessStart() { const string queryString = "SELECT TargetInstance" + " FROM __InstanceCreationEvent " + "WITHIN 10 " + " WHERE TargetInstance ISA 'Win32_Process' " + " AND TargetInstance.Name = 'lync.exe'"; // The dot in the scope means use the current machine const string scope = @"\\.\root\CIMV2"; // Create a watcher and listen for events _managementEventWatcher = new ManagementEventWatcher(scope, queryString); _managementEventWatcher.EventArrived += WatcherEventArrived; _managementEventWatcher.Start(); }
public void Stop() { if (_watcher != null) { _watcher?.Stop(); _watcher.EventArrived -= new EventArrivedEventHandler(Watcher_EventArrived); _watcher = null; } if (_comConnection != null) { _comConnection.Disconnect(); _comConnection.RfidReceived -= ComConnection_RfidReceived; _comConnection = null; } }
static void WaitForProcess() { try { var startWatch = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace")); startWatch.EventArrived += new EventArrivedEventHandler(startWatch_EventArrived); startWatch.Start(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"+ Listening for the following processes: {string.Join(" ", processList)}\n"); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(ex); } }
public static void Main() { WMIEvent we = new WMIEvent(); ManagementEventWatcher w= null; WqlEventQuery q; try { q = new WqlEventQuery(); q.EventClassName = "Win32_ProcessStartTrace"; w = new ProcessStartEventArrived(q); w.EventArrived += new EventArrivedEventHandler(we.ProcessStartEventArriv ed); w.Start(); Console.ReadLine(); // block main thread for test purposes } finally { w.Stop(); } }
/// <summary> /// The watch for process start. /// </summary> /// <param name="processName"> /// The process name. /// </param> /// <returns> /// The <see cref="ManagementEventWatcher"/>. /// </returns> // ReSharper disable once UnusedMember.Local private ManagementEventWatcher WatchForProcessStart(string processName) { string queryString = "SELECT TargetInstance" + " FROM __InstanceCreationEvent " + "WITHIN 10 " + " WHERE TargetInstance ISA 'Win32_Process' " + " AND TargetInstance.Name = '" + processName + "'"; // The dot in the scope means use the current machine const string Scope = @"\\.\root\CIMV2"; // Create a watcher and listen for events ManagementEventWatcher watcher = new ManagementEventWatcher(Scope, queryString); watcher.EventArrived += this.ProcessStarted; watcher.Start(); return(watcher); }
public void WaitForProcess(object sender, DoWorkEventArgs e) { ManagementEventWatcher startWatch = new ManagementEventWatcher( new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace")); startWatch.EventArrived += this.StartWatchEventArrived; startWatch.Start(); ManagementEventWatcher stopWatch = new ManagementEventWatcher( new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace")); stopWatch.EventArrived += this.StopWatchEventArrived; stopWatch.Start(); }
static public void Start() { deviceList = new List <String>(); // First Scan foreach (String port in SerialPort.GetPortNames()) { AddDevice(port); } // Observe Changes deviceChangeEventWatcher = new ManagementEventWatcher(); deviceChangeEventWatcher.EventArrived += new EventArrivedEventHandler(deviceChangeEventArrived); deviceChangeEventWatcher.Query = new WqlEventQuery("__InstanceOperationEvent", new TimeSpan(0, 0, 3), @"TargetInstance ISA 'Win32_USBControllerDevice'"); deviceChangeEventWatcher.Start(); }
public SerialPortManager() { Ports = new List <SerialPortInfo>(GetPortInformations()); eventWatcher = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 or EventType = 3")); eventWatcher.EventArrived += (o, args) => { try { UpdateDeviceList(); } catch { } }; eventWatcher.Start(); }
public void Start() { var query = new WqlEventQuery { QueryString = string.Format(@"SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity' AND TargetInstance.ClassGuid = '{0}'", GUID_DEVCLASS_USB) }; _watcher = new ManagementEventWatcher(); _watcher.EventArrived += watcher_EventArrived; _watcher.Query = query; _watcher.Start(); _log.Info("Started watching for USB devices"); }
/// <summary> /// Main program. /// </summary> /// <param name="args">Command-line parameters</param> /// <seealso cref="https://stackoverflow.com/questions/620144/detecting-usb-drive-insertion-and-removal-using-windows-service-and-c-sharp"/> static void Main(string[] args) { ManagementEventWatcher watcher = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 OR EventType = 3"); watcher.EventArrived += new EventArrivedEventHandler(EventArrived); watcher.Query = query; watcher.Start(); Enumerate(); while (true) { watcher.WaitForNextEvent(); } }
public Form1() { InitializeComponent(); volumeNameTxt.Enabled = changeName.Checked; formatFS.Enabled = format.Checked; formatFS.DataSource = Enum.GetValues(typeof(FileSystem)); formatFS.SelectedIndex = 0; toolStatus.Text = "Ready"; SetUsbList(); ManagementEventWatcher watcher = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent"); watcher.EventArrived += new EventArrivedEventHandler(DriveWatcherEvent); watcher.Query = query; watcher.Start(); }
public override void Enable() { Console.WriteLine("Test"); WqlEventQuery query = new WqlEventQuery(String.Format( System.Globalization.CultureInfo.InvariantCulture, @"SELECT * FROM RegistryValueChangeEvent WHERE Hive = 'HKEY_USERS' AND Keypath = '{0}' AND (ValueName='SystemUsesLightTheme' OR ValueName='AppsUseLightTheme')", wmiRegistryPath)); watcher = new ManagementEventWatcher(query); watcher.EventArrived += new EventArrivedEventHandler(RegistryKeyChanged); watcher.Start(); RefreshThemeInfo(); }
/// <summary>Stops the monitoring of device.</summary> public void Exit() { //In case same class was called make sure only one instance is running ///////////////////////////////////////////////////////////// if (null != m_managementEventWatcher) { try { m_managementEventWatcher.Stop(); m_managementEventWatcher = null; } catch { } } }