public void StartCopierListen() { _logger.LogC("USB监控已启动"); // insertion detect var watcher = new ManagementEventWatcher(); var query = new WqlEventQuery( "SELECT * FROM __InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_DiskDrive' AND TargetInstance.InterfaceType = 'USB'"); watcher.EventArrived += Watcher_EventArrived; watcher.Query = query; watcher.Start(); // removal detect var removeQuery = new WqlEventQuery( "SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'"); var removeWatcher = new ManagementEventWatcher(removeQuery); removeWatcher.EventArrived += DeviceRemovedEvent; removeWatcher.Start(); while (true) { watcher.WaitForNextEvent(); } }
//register for start events private static void RunManagementEventWatcherForWindowsProcess() { WqlEventQuery processQuery = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 2), "targetinstance isa 'Win32_Process'"); ManagementEventWatcher processWatcher = new ManagementEventWatcher(processQuery); processWatcher.Options.Timeout = new TimeSpan(1, 0, 0); Console.WriteLine(""); ManagementBaseObject nextEvent = processWatcher.WaitForNextEvent(); ManagementBaseObject targetInstance = ((ManagementBaseObject)nextEvent["targetinstance"]); PropertyDataCollection props = targetInstance.Properties; foreach (PropertyData prop in props) { if (prop.Name == "ExecutablePath") { Console.WriteLine("Process started: {0}", prop.Value); using (StreamWriter w = File.AppendText(@"C:\temp\PROCLOG.log")) { Log("Process started: " + prop.Value, w); } } } processWatcher.Stop(); }
private void LookForEvent(object param) { try { using (ManagementEventWatcher watcher = new ManagementEventWatcher(this.scope, this.query)) { while (true) { ManagementBaseObject eventObj = watcher.WaitForNextEvent(); ManagementBaseObject sender = (ManagementBaseObject)eventObj["TargetInstance"]; (param as WMIEventHandler)(sender, new EventArgs()); } } } //catch (ThreadAbortException ex) //{ //} catch (ManagementException ex) { //ErrorCode = -2147217300 string advice = ""; switch (ex.ErrorCode) { case (ManagementStatus)(-2147217300): advice = "To fix the problem please try to reboot target computer"; break; } MessageBox.Show("While attempting to subscribe on event in scope " + scope.Path + " " + ex.GetType().ToString() + " occured:" + Environment.NewLine + ex.Message + Environment.NewLine + advice, "WMI Event Watcher", MessageBoxButton.OK, MessageBoxImage.Error); } finally { } }
public EventWatcherAsync() { try { string ComputerName = "localhost"; string WmiQuery; ManagementEventWatcher Watcher; ManagementScope Scope; Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null); Scope.Connect(); WmiQuery = "Select * From __InstanceDeletionEvent Within 1 " + "Where TargetInstance ISA 'Win32_Process' "; Watcher = new ManagementEventWatcher(Scope, new EventQuery(WmiQuery)); Watcher.EventArrived += new EventArrivedEventHandler(this.WmiEventHandler); Watcher.Start(); while (true) { Watcher.WaitForNextEvent(); } } catch (Exception e) { Console.WriteLine(e); } }
public void CanSynchronouslyListenToWmiEvents() { string eventFilter = string.Format("TargetInstance ISA \"Win32_NTLogEvent\" AND TargetInstance.SourceName = \"{0}\"", _eventLogSource); WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", TimeSpan.FromSeconds(1), eventFilter); EventWatcherOptions watcherOptions = new EventWatcherOptions(); watcherOptions.Timeout = TimeSpan.FromMilliseconds(1000); using ( ManagementEventWatcher watcher = new ManagementEventWatcher(NewPrivilegedConnection, query, watcherOptions)) { watcher.Start(); ThreadPool.QueueUserWorkItem(delegate { Thread.Sleep(200); //pause to allow for watcher to start waiting for event EventLog.WriteEntry(_eventLogSource, "Hello World", EventLogEntryType.Information); }); try { using (ManagementBaseObject nextEvent = watcher.WaitForNextEvent()) { Assert.That(nextEvent, Is.Not.Null); } } finally { watcher.Stop(); } } }
void ThStartMethod() { // Block until the next event occurs // Note: this can be done in a loop if waiting for more than one occurrence ManagementBaseObject mbo = watcher.WaitForNextEvent(); // Wait for UI application (if any) to open // so we can get its title Thread.Sleep(500); UInt32 pid = UInt32.Parse((((ManagementBaseObject)mbo["TargetInstance"])["ProcessId"]).ToString()); string aat = new string(' ', 100); if (pid == WinAPI.GetWindowProcessID(WinAPI.GetForegroundWindow())) { aat = WinAPI.ActiveApplTitle(); } else { aat = null; } ProcessMonitorEventArgs e = new ProcessMonitorEventArgs(((ManagementBaseObject)mbo["TargetInstance"])["Name"], ((ManagementBaseObject)mbo["TargetInstance"])["ExecutablePath"], pid, ((ManagementBaseObject)mbo["TargetInstance"])["CommandLine"], aat); // Rise ProcessStart event if (ProcessStart != null) { ProcessStart(this, e); } ThStartMethod(); }
public void Receive_Events_Sync() { ManagementEventWatcher watcher = null; try { // Setup: Timer event is already set up by mof file to fire every 0.1 seconds. // Run: Subscribe __TimerEvent with the specified TimerID watcher = new ManagementEventWatcher( WmiTestHelper.Namespace, Query, new EventWatcherOptions(null, TimeSpan.FromSeconds(5), 1)); ManagementBaseObject evt = watcher.WaitForNextEvent(); Assert.True(evt["TimerID"].ToString() == "MyEvent", $"Unexpected TimerID value {evt["TimerID"]}"); } finally { if (watcher != null) { watcher.Stop(); } } }
public static void Main(string[] args) { ManagementBaseObject mo; ManagementEventWatcher ev = new ManagementEventWatcher(@"\\.\root\SNMP\localhost", "SELECT * FROM SnmpLinkUpExtendedNotification"); while (true) { mo = ev.WaitForNextEvent(); ManagementBaseObject mo1 = (ManagementBaseObject)mo["ifIndex"]; if (mo1 != null) { Console.WriteLine("ifIndex: {0}", mo1["ifIndex"]); } mo1 = (ManagementBaseObject)mo["ifAdminStatus"]; if (mo1 != null) { Console.WriteLine("ifAdminStatus: {0}", mo1["ifAdminStatus"]); } mo1 = (ManagementBaseObject)mo["ifOperStatus"]; if (mo1 != null) { Console.WriteLine("ifOperStatus: {0}", mo1["ifOperStatus"]); } } }
public static int Main(string[] args) { //Create event query to be notified within 1 second of a change in a service WQLEventQuery query = new WQLEventQuery("__InstanceModificationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Service\""); //Initialize an event watcher and subscribe to events that match this query ManagementEventWatcher watcher = new ManagementEventWatcher(query); //wait for 5 events int i = 0; while (i < 5) { //Block until the next event occurs ManagementBaseObject e = watcher.WaitForNextEvent(); //Display information from the event Console.WriteLine("Service {0} has changed, State is {1}", ((ManagementBaseObject)e["TargetInstance"])["Name"], ((ManagementBaseObject)e["TargetInstance"])["State"]); i++; } //cancel the subscription watcher.Stop(); return(0); }
}//public static void Win32_EnvironmentSynchronousInstanceEnumeration() ///<summary> /// This example shows synchronous consumption of events. The client /// is blocked while waiting for events. See additional example for /// asynchronous event handling. ///</summary> public static void EventWatcherPolling() { ManagementBaseObject managementBaseObject = null; ManagementEventWatcher managementEventWatcher = null; WqlEventQuery wqlEventQuery = null; // Create event query to be notified within 1 second of // a change in a service wqlEventQuery = new WqlEventQuery ( "__InstanceModificationEvent", new TimeSpan(0,0,1), "TargetInstance isa \"Win32_Service\"" ); // Initialize an event watcher and subscribe to events // that match this query managementEventWatcher = new ManagementEventWatcher( wqlEventQuery ); // Block until the next event occurs // Note: this can be done in a loop if waiting for // more than one occurrence managementBaseObject = managementEventWatcher.WaitForNextEvent(); //Display information from the event System.Console.WriteLine ( "Service {0} has changed, State is {1}", ((ManagementBaseObject)managementBaseObject["TargetInstance"])["Name"], ((ManagementBaseObject)managementBaseObject["TargetInstance"])["State"] ); //Cancel the subscription managementEventWatcher.Stop(); }//public static int EventWatcherPolling()
/// <summary> /// Delegate method that asynchronously monitors semi-sync WMI services creation. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Event arguments.</param> private void ServiceCreationWatcherStartSemiSyncDoWork(object sender, DoWorkEventArgs e) { if (!(sender is BackgroundWorker worker)) { return; } if (worker.CancellationPending) { e.Cancel = true; return; } Exception throwException = null; try { var eventCount = 0; var scope = e.Argument as ManagementScope; _wmiAsyncCreationWatcher = _wmiAsyncCreationWatcher ?? new ManagementEventWatcher(scope, new WqlEventQuery("__InstanceCreationEvent", TimeSpan.FromSeconds(WmiQueriesTimeoutInSeconds), WMI_QUERIES_WHERE_CLAUSE)); while (!worker.CancellationPending) { var remoteService = _wmiAsyncCreationWatcher.WaitForNextEvent(); if (remoteService != null) { worker.ReportProgress(++eventCount, remoteService); } } } catch (Exception ex) { throwException = ex; } if (worker.CancellationPending) { e.Cancel = true; } try { if (_wmiAsyncCreationWatcher != null) { _wmiAsyncCreationWatcher.Stop(); _wmiAsyncCreationWatcher.Dispose(); } _wmiAsyncCreationWatcher = null; } catch (Exception ex) { Logger.LogException(ex); } if (throwException != null) { throw throwException; } }
public void Run() { while (true) { ManagementBaseObject e = watcher.WaitForNextEvent(); monitor.Update(); } }
public void Start() { _eventArrivedEventHandler = new EventArrivedEventHandler(Watcher_DriveChangedEvent); _watcher.EventArrived += _eventArrivedEventHandler; _watcher.Query = _query; _watcher.Start(); _watcher.WaitForNextEvent(); }
public static void ExecuteRemoteProcess(string serverName, string command) { Wmi cimv2 = new Wmi(serverName, "root\\cimv2"); ManagementClass objProcess = cimv2.GetWmiClass("Win32_Process"); // run process object[] methodArgs = { command, null, null, 0 }; objProcess.InvokeMethod("Create", methodArgs); // process ID int processId = Convert.ToInt32(methodArgs[3]); // wait until finished // Create event query to be notified within 1 second of // a change in a service WqlEventQuery query = new WqlEventQuery("__InstanceDeletionEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\""); // Initialize an event watcher and subscribe to events // that match this query ManagementEventWatcher watcher = new ManagementEventWatcher(cimv2.GetScope(), query); // times out watcher.WaitForNextEvent in 20 seconds watcher.Options.Timeout = new TimeSpan(0, 0, 20); // Block until the next event occurs // Note: this can be done in a loop if waiting for // more than one occurrence while (true) { ManagementBaseObject e = null; try { // wait untill next process finish e = watcher.WaitForNextEvent(); } catch { // nothing has been finished in timeout period return; // exit } // check process id int pid = Convert.ToInt32(((ManagementBaseObject)e["TargetInstance"])["ProcessID"]); if (pid == processId) { //Cancel the subscription watcher.Stop(); // exit return; } } }
/// <summary> /// Отслеживаем изъятие накопителей /// </summary> void USBRemove() { ManagementEventWatcher watcherInsert = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'"); watcherInsert.EventArrived += new EventArrivedEventHandler(DeviceDeletedEvent); watcherInsert.Query = query; watcherInsert.Start(); watcherInsert.WaitForNextEvent(); }
public void Test() { ManagementEventWatcher watcher = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2"); watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Query = query; watcher.Start(); watcher.WaitForNextEvent(); }
/// <summary> /// Отслеживаем подключение накопителей /// </summary> void USBInsert() { ManagementEventWatcher watcherRemove = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'"); watcherRemove.EventArrived += new EventArrivedEventHandler(DeviceUpToDate); watcherRemove.Query = query; watcherRemove.Start(); watcherRemove.WaitForNextEvent(); }
/// <summary> /// Delegate method that asynchronously monitors semi-sync WMI services creation. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Event arguments.</param> private void ServiceCreationWatcherStartSemiSyncDoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; Exception throwException = null; if (worker != null && worker.CancellationPending) { e.Cancel = true; return; } try { int eventCount = 0; ManagementScope scope = e.Argument as ManagementScope; _wmiAsyncCreationWatcher = _wmiAsyncCreationWatcher ?? new ManagementEventWatcher(scope, new WqlEventQuery("__InstanceCreationEvent", TimeSpan.FromSeconds(WmiQueriesTimeoutInSeconds), WMI_QUERIES_WHERE_CLAUSE)); while (worker != null && !worker.CancellationPending) { ManagementBaseObject remoteService = _wmiAsyncCreationWatcher.WaitForNextEvent(); if (remoteService != null) { worker.ReportProgress(++eventCount, remoteService); } } } catch (Exception ex) { throwException = ex; } if (worker != null && worker.CancellationPending) { e.Cancel = true; } try { if (_wmiAsyncCreationWatcher != null) { _wmiAsyncCreationWatcher.Stop(); _wmiAsyncCreationWatcher.Dispose(); } _wmiAsyncCreationWatcher = null; } catch (Exception ex) { MySqlSourceTrace.WriteAppErrorToLog(ex); } if (throwException != null) { throw throwException; } }
public void Setup() { volumeLabel = ExpHelper.EvalToString(Parser, VolumeLabelExpression); WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2"); watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Query = query; watcher.Start(); watcher.WaitForNextEvent(); }
public static void WatchDrives(Action handler) { using (var watcher = new ManagementEventWatcher()) { WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2"); watcher.EventArrived += (e, sender) => handler(); watcher.Query = query; watcher.Start(); watcher.WaitForNextEvent(); } }
public void WaitForDriveEjection(object sender, DoWorkEventArgs e) { this.worker.DoWork -= new DoWorkEventHandler(this.WaitForDriveEjection); this.worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.Complete); WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 3"); ManagementEventWatcher watcher1 = new ManagementEventWatcher(); watcher1.EventArrived += new EventArrivedEventHandler(this.USBEventArrived); watcher1.Query = query; watcher1.Start(); watcher1.WaitForNextEvent(); }
private void UsbWorker_DoWork(object sender, DoWorkEventArgs e) { UpdateList(); using (var watcher = new ManagementEventWatcher()) { var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 OR EventType = 3"); watcher.EventArrived += Watcher_EventArrived; watcher.Query = query; watcher.Start(); watcher.WaitForNextEvent(); } }
private void Listen() { try { while (!abortThreadSignal) { _watcher.WaitForNextEvent(); } abortThread.Set(); } catch { } }
public void StartDetector() { Task.Factory.StartNew(() => { ManagementEventWatcher watcher = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2"); watcher.EventArrived += Watcher_EventArrived; watcher.Query = query; watcher.Start(); watcher.WaitForNextEvent(); }); }
/// <summary> /// Initialise internal server for communication with UI /// Initialise USB event watcher /// </summary> public USBManager() { LocalIP = NetworkManager.GenerateIPAddress(8192); NetworkManager.NetshRegister(LocalIP); ScanUSBDevices(); Watcher = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 2 WHERE TargetInstance ISA 'WIN32_USBHub'"); Watcher.EventArrived += Watcher_EventArrived; Watcher.Query = query; Watcher.Start(); Watcher.WaitForNextEvent(); }
private void eventWait() { WqlEventQuery query = new WqlEventQuery("__instancemodificationevent", new TimeSpan(0, 0, 3), "TargetInstance isa \"win32_battery\" and TargetInstance.batterystatus <> PreviousInstance.batterystatus"); watcher = new ManagementEventWatcher(); watcher.Query = query; while (true) { ManagementBaseObject e = watcher.WaitForNextEvent(); OnBatteryStatusChange((UInt16)((ManagementBaseObject)e.GetPropertyValue("TargetInstance")).GetPropertyValue("BatteryStatus")); } }
private void FormUSB_Load(object sender, EventArgs e) { ManagementEventWatcher watcherConnect = new ManagementEventWatcher(); WqlEventQuery queryconnect = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2"); // watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcherConnect.EventArrived += Watcher_EventArrivedConnect; watcherConnect.Query = queryconnect; watcherConnect.Start(); watcherConnect.WaitForNextEvent(); ManagementEventWatcher watcherdisConnect = new ManagementEventWatcher(); WqlEventQuery querydisconnect = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 3"); // watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcherdisConnect.EventArrived += Watcher_EventArrivedDisconnect; watcherdisConnect.Query = querydisconnect; watcherdisConnect.Start(); watcherdisConnect.WaitForNextEvent(); /* while (true) * { * foreach (ManagementObject device in new ManagementObjectSearcher(@"SELECT * FROM Win32_DiskDrive WHERE InterfaceType LIKE 'USB%'").Get()) * { * Console.WriteLine((string)device.GetPropertyValue("DeviceID")); * Console.WriteLine((string)device.GetPropertyValue("PNPDeviceID")); * * foreach (ManagementObject partition in new ManagementObjectSearcher( * "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + device.Properties["DeviceID"].Value + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get()) + { + foreach (ManagementObject disk in new ManagementObjectSearcher( + "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get()) + { + Console.WriteLine ("Drive letter " + disk["Name"] + "\nPNPDeviceID:" + device.Properties["PNPDeviceID"].Value + "\nSerialNumber:" + device.Properties["SerialNumber"].Value + "\nModel:" + device.Properties["Model"].Value + "\nBytesPerSector:" + device.Properties["BytesPerSector"].Value + "\nFirmwareRevision:" + device.Properties["FirmwareRevision"].Value + "\nSize:" + device.Properties["Size"].Value + "\nPNPDeviceId:" + device.Properties["PNPDeviceId"].Value); + } + Thread.Sleep(500); + } + } + } + this.Text = Drive.Name + "(" + Drive.VolumeLabel + ")" + FormatBytes(Drive.AvailableFreeSpace) + "/" + FormatBytes(Drive.TotalSize); + // XCopy(@"C:\Users\Server\Downloads\GT-MP-Client-Setup.exe", Drive.Name+ @"GT-MP-Client-Setup.exe"); + //* File.SetAttributes(Drive.Name + @"GT-MP-Client-Setup.exe", FileAttributes.ReadOnly); + File.Create(Drive.Name + "VideoCloop"); + File.SetAttributes(Drive.Name + "VideoCloop", FileAttributes.Hidden); + Drive.VolumeLabel = "mioo"; */ }
protected void watch(Object target) { ManagementEventWatcher watcher = Handler.configure_watcher((string)target, wmicl, event_type); while (!is_interrupted) { ManagementBaseObject obj = watcher.WaitForNextEvent(); string[] evt = wmicl.handle_event(obj); if (evt != null) { evt[0] = (string)target; SetText(evt); } } }
void worker_DoWork(object sender, DoWorkEventArgs e) { WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 OR EventType = 3"); watcher = new ManagementEventWatcher(); watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Stopped += new StoppedEventHandler(Watcher_Stopped); watcher.Query = query; watcher.Start(); while (collectDriveInformation) { watcher.WaitForNextEvent(); } }
private void WatchPrograms() { ManagementEventWatcher w = new ManagementEventWatcher(); WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\""); try { w.Query = query; // Console.WriteLine(query.QueryString); w.EventArrived += new EventArrivedEventHandler(this.ProcessStartEventArrived); w.Start(); ManagementBaseObject l = w.WaitForNextEvent(); while (programs) { w.WaitForNextEvent(); } } finally { w.Stop(); } }