private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e) { ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; foreach (var property in instance.Properties) { Console.WriteLine(property.Name + " = " + property.Value); if (property.Name.Equals("DeviceID")) { foreach (var userSID in GetLocalUserAccounts()) { } } } }
static void startWatchingApp(object sender, EventArrivedEventArgs e) { String processName = (String)e.NewEvent.Properties["ProcessName"].Value; uint pid = (uint)e.NewEvent.Properties["ProcessID"].Value; if (appsToWatch.Contains(processName)) { addProcessToRunningApps(pid, processName); killMiner(); } else { Console.WriteLine("Unwatched process started: {0}, {1}", processName, pid); } }
/// <summary> /// Called on arrival of any device. /// Calls a routine that searches to see if the desired device is present. /// </summary> private void DeviceAdded(object sender, EventArrivedEventArgs e) { try { Console.WriteLine("A USB device has been inserted"); FindMyDevice(); //_deviceDetected = FindDeviceUsingWmi(); } catch (Exception ex) { DisplayException(Name, ex); throw; } }
private void getEventWatcher_EventArrived(object sender, EventArrivedEventArgs e) { ManagementBaseObject getBaseObject = (ManagementBaseObject)e.NewEvent; if ((getBaseObject.ClassPath.ClassName == "__InstanceCreationEvent")) { //Usb Inserted MessageBox.Show("USB Disk Inserted!"); } else { //Usb Removed MessageBox.Show("USB Device Removed!"); } }
private void Device_Removed(object sender, EventArrivedEventArgs e) { var instance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; var deviceInfo = new UsbDeviceInfo( instance.GetPropertyValue("DeviceID").ToStringOrEmpty(), instance.GetPropertyValue("PNPDeviceID").ToStringOrEmpty(), instance.GetPropertyValue("Description").ToStringOrEmpty() ); if (this.OnDeviceRemoved != null && this.EnableRaisingEvents) { this.OnDeviceRemoved(this, new EventArgs <UsbDeviceInfo>(deviceInfo)); } }
private void ProcessEndEvent(object sender, EventArrivedEventArgs e) { ManagementBaseObject newEvent = e.NewEvent; ManagementBaseObject targetInstance = (ManagementBaseObject)newEvent["TargetInstance"]; ApplicationInfo info = new ApplicationInfo { Name = this.GetProcessName(targetInstance), PPID = (int)(UInt32)targetInstance.Properties["ProcessId"].Value, StartTime = null, EndTime = DateTime.Now, IsRunning = false }; this.storage.CurrentState.MergeWith(info); }
static void processStartedEvent(object sender, EventArrivedEventArgs e) { ManagementBaseObject proc = (ManagementBaseObject)( (ManagementBaseObject)e.NewEvent ) ["TargetInstance"]; if ((string)proc["Name"] != "youtube-dl.exe") { return; } Console.WriteLine( DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss ") + proc["CommandLine"] ); }
private void EventWatcher_EventArrived(object sender, EventArrivedEventArgs e) { var changed = WqlHelper.ParseEventArrivedEventArgs(e); T oldItem = default(T), newItem = default(T); if (changed.Item1 != null) { oldItem = ConvertItem(changed.Item1); } if (changed.Item2 != null) { newItem = ConvertItem(changed.Item2); } if (IsSameItem(oldItem, newItem)) { //Nothing relevant is changed. return; } var args = new WmiMonitorEventArgs <T>(); bool updateResult; args.NewEvent = e.NewEvent; args.OldValue = oldItem; args.NewValue = newItem; cacheLock.EnterWriteLock(); if (IsSameItem(oldItem, null) && !IsSameItem(newItem, null)) { args.Operation = ItemOperation.Remove; updateResult = AddOrDeleteItem(changed.Item1, false); } else if (!IsSameItem(oldItem, null) && IsSameItem(newItem, null)) { args.Operation = ItemOperation.Add; updateResult = AddOrDeleteItem(changed.Item2, true); } else { args.Operation = ItemOperation.Modify; updateResult = AddOrDeleteItem(changed.Item1, false) && AddOrDeleteItem(changed.Item2, true); } cacheLock.ExitWriteLock(); if (updateResult) { cacheLock.EnterReadLock(); ItemUpdated?.Invoke(this, args); cacheLock.ExitReadLock(); } }
/// <summary> /// Detects when a new process launches on the PC, because of URI promises we will also try and update a root managed /// process if /// it is found to be starting up. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void ProcessStarted(object sender, EventArrivedEventArgs e) { try { var targetInstance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; var processId = int.Parse(targetInstance["ProcessId"].ToString()); var processParent = int.Parse(targetInstance["ParentProcessId"].ToString()); var processName = targetInstance["Name"].ToString().Trim(); var processPath = targetInstance.TryGetProperty <string>("ExecutablePath")?.Trim(); if (string.IsNullOrWhiteSpace(processPath)) { processPath = ProcessUtils.GetProcessPath(processId)?.Trim(); if (string.IsNullOrWhiteSpace(processPath)) { processPath = "Unknown"; } } var commandLineArguments = ProcessUtils.GetCommandLineFromString(targetInstance.TryGetProperty <string>("CommandLine")?.Trim()); if (processName == "?" && !processPath.Equals("Unknown")) { try { processName = Path.GetFileName(processPath)?.Trim(); if (string.IsNullOrWhiteSpace(processName)) { processName = "Unknown"; } } catch (Exception ex) { Logger?.Error(ex.ToString()); processName = "Unknown"; } } targetInstance.Dispose(); e.NewEvent.Dispose(); // Logger?.Debug(processName + " / " + processId + " / " + processPath); PreProcessing(processName, processId, processPath, commandLineArguments); HandleNewProcess(processName, processId, processParent, processPath, commandLineArguments); HandleUnknownProcess(processName, processId, processParent, processPath, commandLineArguments); } catch (Exception ex) { Logger?.Error(ex.ToString()); } }
//Launch HVA on Meditech Launch Event private void Watcher_EventArrived(object sender, EventArrivedEventArgs e) { //Do stuff with the startup event //TextBox1.AppendText("Watcher_EventArrived"); trayIcon.Icon = HVA_TrayApp.Properties.Resources.HVA_On; trayIcon.Text = "Meditech is running."; const int WM_USER = 0x400; //MainWindow.VisibilityProperty. //Form2.GetWindowRect(Form2.GetForegroundWindow(), r) System.Diagnostics.Process proc = new System.Diagnostics.Process(); //NotifyIcon1.Icon = My.Resources.HVA_On; //NotifyIcon1.Text = "Meditech is Running"; this.Dispatcher.Invoke(() => { TextBox1.Clear(); }); dynamic procName = Process.GetProcessesByName("T"); foreach (Process procs in procName) { UpdateTextBox(procs.Id); } ProcessStartInfo startInfo = new ProcessStartInfo("\\\\CWDVV1DVAC01\\C$\\Users\\HVU7259\\Desktop\\hva-valuebar.exe"); //startInfo.FileName = "\\\\CWDVV1DVAC01\\C$\\Users\\HVU7259\\Desktop\\hva-valuebar.exe"; //startInfo.RedirectStandardInput = true; //startInfo.RedirectStandardOutput = false; startInfo.UseShellExecute = false; startInfo.WindowStyle = ProcessWindowStyle.Hidden; proc = Process.Start(startInfo); //Path to HVA GUI Thread.Sleep(300); //Wait for hvaHwnd = Form2.WinGetHandle("HVA Valuebar"); // RichTextBox1.AppendText("HVA Handle: " & Form2.GetActiveWindowTitle(Form2.GetForegroundWindow()) & vbCrLf) SendMessage(hvaHwnd, WM_USER + 1000, (IntPtr)0, IntPtr.Zero); ProcessThreadCollection currentThreads = Process.GetCurrentProcess().Threads; this.Dispatcher.Invoke(() => { TextBox1.AppendText("HVA Bar Handle: " + hvaHwnd.ToString() + "\r\n"); }); //, CType(Location.Left + (Location.Top - 80 << 16), IntPtr), CType((Location.Right - Location.Left) + (10 << 16), IntPtr) }
private void VolumeWatcher_EventArrived(object sender, EventArrivedEventArgs e) { var driveName = ((string)e.NewEvent.Properties["DriveName"].Value).Substring(0, 1); var eventType = (EventType)Convert.ToInt16((e.NewEvent.Properties["EventType"].Value)); switch (eventType) { case EventType.Inserted: lock (driveLock) { var driveInfo = new DriveInfo(driveName.ToString()); if (IsDriveTypeSupported(driveInfo.DriveType) && driveInfo.IsReady && DriveList[driveName].EventType != EventType.Inserted) { if (DriveInserted != null) { DriveInserted(null, new VolumeChangedEventArgs() { DriveLetter = driveName, DriveType = driveInfo.DriveType }); } DriveList[driveName].DriveType = driveInfo.DriveType; DriveList[driveName].EventType = EventType.Inserted; } } break; case EventType.Removed: lock (driveLock) { if (IsDriveTypeSupported(DriveList[driveName].DriveType) && DriveList[driveName].EventType != EventType.Initial && DriveList[driveName].EventType != EventType.Removed) { if (DriveRemoved != null) { DriveRemoved(null, new VolumeChangedEventArgs() { DriveLetter = driveName, DriveType = DriveList[driveName].DriveType }); } DriveList[driveName].DriveType = DriveType.Unknown; DriveList[driveName].EventType = EventType.Removed; } } break; } }
void closeWatcher_EventArrived(object sender, EventArrivedEventArgs e) { var instance = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value; var name = (string)instance["Name"]; var pid = (uint)instance["ProcessId"]; if (name == "eldorado.exe" && _gameProcess.ProcessId == pid) { Console.WriteLine("Game process closed."); IsRunning = false; if (ProcessClosed != null) { ProcessClosed(this, EventArgs.Empty); } } }
private void watcher_EventArrived(object sender, EventArrivedEventArgs e) { try { watcher.Stop(); Thread.Sleep(250); Dispatcher.Invoke(Scan, DispatcherPriority.Send); watcher.Start(); } catch (Exception Ex) { MessageBox.Show(Ex.ToString()); } // watcher.ExpiryDate(); }
static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) { String pName = ((String)e.NewEvent.Properties["ProcessName"].Value).ToLowerInvariant(); Logger.GetInstance().Debug(pName + " started"); if (sensitiveProcessesList.Contains(pName)) { if (!activeSensitiveProcesses.Contains(pName)) { activeSensitiveProcesses.Add(pName); } Block(); } }
private void OnEventArrived(object sender, EventArrivedEventArgs e) { try { var eventName = e.NewEvent.ClassPath.ClassName; if (string.Compare(eventName, "__InstanceCreationEvent", StringComparison.Ordinal) == 0) { Started?.Invoke(this, e); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
private void WmiEventHandler(object sender, EventArrivedEventArgs e) { //in this point the new events arrives //you can access to any property of the Win32_Process class string procName = (string)((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Name"]; string pid = (string)((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Handle"]; if (procName.Contains("grimrock2")) { Logger.AppendText("Found LoG2 process with PID " + pid); Logger.AppendText(StringResources.PickDirString); MainForm.LoG2ProcessFound = true; //FoundLoG2Process(null, null); StopWatcher(); } }
private void Watcher_EventArrived(object sender, EventArrivedEventArgs e) { ManagementBaseObject o = (ManagementBaseObject)e.NewEvent["TargetInstance"]; int pid = (int)(UInt32)o["ProcessId"]; LOG.DebugFormat("Watcher_EventArrived - PID: {0}", pid); Process p = Process.GetProcessById(pid); if (_forms.Any(form => form.OwnsProcess(p))) { LOG.DebugFormat("Watcher_EventArrived - Process opened by child - PID: {0}", p.Id); return; } this.UiBeginInvoke((Func <Process, Task>)CaptureNewProcess, p); }
public static async void gameWatch_EventArrived(object sender, EventArrivedEventArgs e) { if (Properties.Settings.Default.BoostRAMToggle) { try { var pid = int.Parse(e.NewEvent.Properties["ProcessId"].Value.ToString()); Process p = Process.GetProcessById(pid); MyProcesses.EmptyWorkingSet(p); } catch (Exception ex) { Console.WriteLine($"Exception occured in queuer... {ex.Message}"); } } }
private void USBEventHandler(object sender, EventArrivedEventArgs e) { if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent") { Program.logIt("USB plug in time:" + DateTime.Now); } else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent") { Program.logIt("USB plug out time:" + DateTime.Now); } foreach (EZUSB.USBControllerDevice Device in EZUSB.WhoUSBControllerDevice(e)) { Program.logIt("\tAntecedent:" + Device.Antecedent); Program.logIt("\tDependent:" + Device.Dependent); } }
private void DeviceRemoving(object sender, EventArrivedEventArgs e) { ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; string PNPDeviceID = instance.Properties["PNPDeviceID"].Value.ToString(); string connectorid = (from x in AttachedDevices where x.Value == PNPDeviceID select x.Key).SingleOrDefault <string>(); if (connectorid != null) { AttachedDevices.Remove(connectorid); Helpers.Win32Helper.CleanAttachedDevice(PNPDeviceID, out string connId_removed); DevRemovingEvent(new DevEventArgs() { ConnectorId = connectorid }); } }
private void DeviceRemovedEvent(object sender, EventArrivedEventArgs e) { var instance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; foreach (var property in instance.Properties) { if (property.Name.Equals("Description") || (property.Name.Equals("DeviceID"))) { if (_DeviceList.Contains(property.Value.ToString())) { _logger.Info(DateTime.Now + " : Отключено: " + property.Value.ToString()); SendMessageFromSocket(_serverIP, 13000, property.Value.ToString()); } } } }
public void watcher_Event_add(object sender, EventArrivedEventArgs e) { this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { foreach (string s in System.IO.Ports.SerialPort.GetPortNames()) { // Check whether new one exist or not if (com_port_list.ContainsKey(s) == false) { comboBoxUartPorts.Items.Add(s); comboBoxUartPorts.SelectedIndex = comboBoxUartPorts.Items.Count - 1; com_port_list.Add(s, comboBoxUartPorts.SelectedIndex); } } })); }
/// <summary> /// Handles the EventArrived event of the _deviceWatcher control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArrivedEventArgs"/> instance containing the event data.</param> private void _deviceWatcher_EventArrived(object sender, EventArrivedEventArgs e) { if (count == 5) { DiscoverDoerSMSDevices(); count++; } else { count++; if (count > 5) { count = 0; } } }
private void ManagementEventWatcherOnEventArrived(object sender, EventArrivedEventArgs eventArrivedEventArgs) { if (eventArrivedEventArgs.NewEvent.ClassPath.RelativePath == "__InstanceCreationEvent") { OnMbedAttachedEvent(MbedAttachedStatus.Attached); StopListening(); ListenforMbedDetach(); } if (eventArrivedEventArgs.NewEvent.ClassPath.RelativePath == "__InstanceDeletionEvent") { OnMbedAttachedEvent(MbedAttachedStatus.Detached); StopListening(); ListenforMbedAttach(); } }
void OnProcessProcStop(object sender, EventArrivedEventArgs e) { var logprefix = "ProcessMon.ProcStop: "; var pid = (uint)e.NewEvent.Properties["ProcessID"].Value; lock (processInfosLock) { if (processInfos.ContainsKey(pid)) { processInfos.Remove(pid); Log(logprefix + $"{pid} ({e.NewEvent.Properties["ProcessName"].Value}): forgetting"); return; } } Log(logprefix + $"{pid} ({e.NewEvent.Properties["ProcessName"].Value}): UNKNOWN, skipping"); }
private void HandleDeviceInstance(object sender, EventArrivedEventArgs args) { if (m_subscribers != null) { ManagementBaseObject deviceEvent = args.NewEvent; if (deviceEvent.ClassPath.ClassName.Equals("__InstanceCreationEvent")) { m_subscribers(DeviceChanged.DeviceArrival); } else if (deviceEvent.ClassPath.ClassName.Equals("__InstanceDeletionEvent")) { m_subscribers(DeviceChanged.DeviceRemoval); } } }
public static USBControllerDevice[] WhoUSBControllerDevice(EventArrivedEventArgs e) { ManagementBaseObject mbo = e.NewEvent["TargetInstance"] as ManagementBaseObject; if (mbo != null && mbo.ClassPath.ClassName == "Win32_USBControllerDevice") { String Antecedent = (mbo["Antecedent"] as String).Replace("\"", String.Empty).Split(new Char[] { '=' })[1]; String Dependent = (mbo["Dependent"] as String).Replace("\"", String.Empty).Split(new Char[] { '=' })[1]; return(new USBControllerDevice[1] { new USBControllerDevice { Antecedent = Antecedent, Dependent = Dependent } }); } return(null); }
private void OnInstanceCreated(object sender, EventArrivedEventArgs e) { try { Trace_n("InstanceCreated event triggered", ""); _instanceCreated?.Invoke(sender, e); var procs = GetTargetProcesses(); if (procs.Count == 0) { return; } AddEventHandlers(procs); } catch (Exception ex) { LogError("OnInstanceCreated", ex); } }
private void StatusWatcherOnEventArrived(object sender, EventArrivedEventArgs e) { var instance = GetTargetInstance(e); var vmId = Guid.Parse(instance.GetPropertyValue("Name") as string ?? throw new InvalidOperationException()); var enabledState = (ushort)instance.GetPropertyValue("EnabledState"); var otherEnabledState = (string)instance.GetPropertyValue("OtherEnabledState"); var healthState = (ushort)instance.GetPropertyValue("HealthState"); _bus.SendLocal(new VirtualMachineStateChangedEvent { VmId = vmId, State = StateConverter.ConvertVMState(enabledState, otherEnabledState, healthState) }); }
private void startWatch_EventArrived(object sender, EventArrivedEventArgs e) { string processName = e.NewEvent.Properties["ProcessName"].Value as string; int processId = Convert.ToInt32(e.NewEvent.Properties["ProcessId"].Value); _log.Debug($"New Process Started: {processName}|{processId}"); if (processName.ToLower().StartsWith(_mainProcessName)) { _log.Info("This should be VPinball. Searching for MAME-Window"); if (_delay > 0) { System.Threading.Thread.Sleep(_delay * 1000); } EnumerateProcessWindowHandles(processId); } }
private void EventRecordWritten(object sender, EventArrivedEventArgs e) { if (OnNewLogEntry != null) { string xml = RemoveAllNamespaces(XElement.Parse(e.NewEvent.GetText(TextFormat.WmiDtd20))).ToString(); using (StringReader stream = new StringReader(xml)) { XPathDocument xpath = new XPathDocument(stream); XPathNavigator navigator = xpath.CreateNavigator(); XPathNodeIterator iter = navigator.Select("/INSTANCE/PROPERTY.OBJECT/VALUE.OBJECT/INSTANCE/PROPERTY[@NAME='EventCode']/VALUE"); if (iter.Count == 1 && iter.MoveNext()) { int eventid; if (!Int32.TryParse(iter.Current.Value, out eventid)) eventid = -1; OnNewLogEntry(eventid, new NewLogEntryArguments() { xml = xml, navigator = navigator }); } } } }
/// <summary> /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void HandleEvent(object sender, EventArrivedEventArgs e) { Console.WriteLine("Received an event."); // RegistryKeyChangeEvent occurs here; do something. }