// Try to unregister the event handler and stop monitoring private void btnStop_Click(object sender, EventArgs e) { if (lstMonitoringItems.SelectedItems.Count == 1) { MonitoringItem item = null; MyEventViewer.MonitoringItems.TryGetValue( lstMonitoringItems.SelectedItems[0].Text, out item); if (item.State == MonitoringItemState.Running) { try { item.StopMonitoring(); item.WmiEventReceived -= MyEventViewer.HandleEvent; UpdateQueryListView(); } catch (Exception ex) { MessageBox.Show("Can not stop monitoring" + " for the following reason:" + Environment.NewLine + ex.Message); } } } }
// Clicking btnRemove should do two things: // 1. Remove the selected element from the monitoredItems dictionary // 2. Remove the selected element from the ListView private void btnRemove_Click(object sender, EventArgs e) { if (lstMonitoringItems.SelectedItems.Count == 1) { MonitoringItem item = null; MyEventViewer.MonitoringItems.TryGetValue( lstMonitoringItems.SelectedItems[0].Name, out item); item.StopMonitoring(); MyEventViewer.MonitoringItems.Remove(item.Name); // Select the item after the one that got deleted // If the last item is deleted select the new // last item in the list int deletedIndex = lstMonitoringItems.SelectedItems[0].Index; lstMonitoringItems.SelectedItems[0].Remove(); if (lstMonitoringItems.Items.Count > deletedIndex) { lstMonitoringItems.Items[deletedIndex].Selected = true; } else if (lstMonitoringItems.Items.Count > 1) { lstMonitoringItems.Items [lstMonitoringItems.Items.Count - 1].Selected = true; } } else { MessageBox.Show("Please select the monitoring item" + " you want to delete"); } }