本文整理汇总了C#中System.Management.ManagementEventWatcher.Stop方法的典型用法代码示例。如果您正苦于以下问题:C# ManagementEventWatcher.Stop方法的具体用法?C# ManagementEventWatcher.Stop怎么用?C# ManagementEventWatcher.Stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Management.ManagementEventWatcher
的用法示例。
在下文中一共展示了ManagementEventWatcher.Stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendLogEntry
void SendLogEntry(WmiTraceListener listener,
LogEntry logEntry)
{
ManagementScope scope = new ManagementScope(@"\\." + wmiPath);
scope.Options.EnablePrivileges = true;
StringBuilder sb = new StringBuilder("SELECT * FROM ");
sb.Append("LogEntryV20");
string query = sb.ToString();
EventQuery eq = new EventQuery(query);
using (ManagementEventWatcher watcher = new ManagementEventWatcher(scope, eq))
{
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Start();
LogSource source = new LogSource("notfromconfig", SourceLevels.All);
source.Listeners.Add(listener);
source.TraceData(TraceEventType.Error, 1, logEntry);
BlockUntilWMIEventArrives();
watcher.Stop();
}
}
示例2: USBRemoveWacher
/// <summary>
/// USB 插入和拔出监测函数。
/// 使用ManagementEventWacher来预定特定系统事件,通过WqlEventQuery设置查询对象和条件以及其他属性(比如查询的轮询间隔),
/// 通过ManagementScope设置查询路径范围。
/// </summary>
public void USBRemoveWacher()
{
ManagementEventWatcher wacher = null;
WqlEventQuery query = null;
ManagementScope scope = null;
try
{
scope = new ManagementScope("root\\CIMV2"); //设置WMI路径
query = new WqlEventQuery(); //设置查询的事件类名,条件,查询间隔,也可一次在构造函数中初始化
query.EventClassName = "__InstanceDeletionEvent";
query.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
query.WithinInterval = new TimeSpan(1000);
wacher = new ManagementEventWatcher(scope, query);
wacher.EventArrived += new EventArrivedEventHandler(onUSBRemoved);
wacher.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
this.Closed += (s, e) =>
{
wacher.Stop();
wacher.Dispose();
};
}
示例3: AddInsertUSBHandler
private void AddInsertUSBHandler()
{
WqlEventQuery query;
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;
ManagementEventWatcher watcher = null;
try
{
query = new WqlEventQuery();
query.EventClassName = "__InstanceCreationEvent";
query.WithinInterval = new TimeSpan(0, 0, 3);
query.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += USBInserted;
watcher.Start();
}
catch(Exception e)
{
if (watcher != null)
{
watcher.Stop();
}
throw e;
}
}
示例4: Run
public static void Run()
{
// Create event query to be notified within 1 second of
// a new process being created
WqlEventQuery query =
new WqlEventQuery("__InstanceCreationEvent",
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(query);
// times out watcher.WaitForNextEvent in 5 seconds
watcher.Options.Timeout = new TimeSpan(0, 0, 5);
// Block until the next event occurs
// Note: this can be done in a loop if waiting for
// more than one occurrence
Console.WriteLine(
"Open an application (notepad.exe) to trigger an event.");
ManagementBaseObject e = watcher.WaitForNextEvent();
log.Debug(e.GetText(TextFormat.Mof ));
ManagementBaseObject target = (ManagementBaseObject)e["TargetInstance"];
Object targetName = target["Name"];
Object targetPath = target["ExecutablePath"];
//Display information from the event
log.Info(
"Process {0} has been created, path is: " + targetName + ", " + targetPath);
//Cancel the subscription
watcher.Stop();
}
示例5: AddRemoveUSBHandler
static void AddRemoveUSBHandler()
{
WqlEventQuery q;
try
{
q = new WqlEventQuery();
q.EventClassName = "__InstanceDeletionEvent";
q.WithinInterval = pollInterval;
//q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
q.Condition = "TargetInstance ISA 'Win32_PnPEntity'";
//w = new ManagementEventWatcher(scope, q);
w = new ManagementEventWatcher(q);
w.EventArrived += USBRemoved;
w.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
if (w != null)
{
w.Stop();
}
}
}
示例6: WaitForAsync
public Task WaitForAsync(string name, CancellationToken cancellationToken)
{
_logger.WriteLine("Attempting {0} wait.", IsEfficient ? "efficient" : "inefficient");
var taskSource = new TaskCompletionSource<object>();
var query = IsEfficient
? new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName = '" + name + "'")
: new EventQuery("SELECT TargetInstance FROM __InstanceCreationEvent WITHIN 0.5 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name LIKE '" + name + "'");
ManagementEventWatcher watcher = null;
try {
watcher = new ManagementEventWatcher(query);
cancellationToken.Register(() => {
_logger.WriteLine("Received Cancel while waiting for '{0}'.", name);
watcher.Stop();
watcher.Dispose();
taskSource.TrySetCanceled();
});
watcher.EventArrived += (sender, e) => {
_logger.WriteLine("Received process start event for '{0}'.", name);
watcher.Stop();
watcher.Dispose();
taskSource.TrySetResult(null);
};
try {
watcher.Start();
}
catch (ManagementException) {
if (!IsEfficient)
throw;
watcher.Dispose();
IsEfficient = false;
return WaitForAsync(name, cancellationToken);
}
}
catch (Exception) {
if (watcher != null)
watcher.Dispose();
throw;
}
return taskSource.Task;
}
示例7: Main
static void Main(string[] args)
{
string dirToWatch = "C:\\\\SSIS\\\\Files\\\\Tyson\\\\BI\\\\Incoming\\\\";
string dirDest = "\\\\\\\\whqwssissb02\\\\SSIS\\\\Files\\\\Tyson\\\\BI\\\\Incoming\\\\";
string dirLog = "C:\\\\SSIS\\\\Files\\\\Tyson\\\\BI\\\\";
string logFileName = "SSISIncomingDirectoryWatcher.log";
string drive = Regex.Replace(dirToWatch, @"(.*:).*", "$1");
string path = Regex.Replace(dirToWatch, @".*:(.*)", "$1");
FileInfo file;
TextWriter tw = File.CreateText(dirLog + logFileName);
// Create a query to be notified within 1 second of a file creation
WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"CIM_DataFile\" AND "
+ "TargetInstance.Drive=\"" + drive + "\" AND "
+ "TargetInstance.Path=\"" + path + "\"");
// Initialize an event watcher and subscribe to events that match this query
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
// Block until the next event occurs
ManagementBaseObject e = watcher.WaitForNextEvent();
string name = (string)((ManagementBaseObject)e["TargetInstance"])["Name"];
file = new FileInfo(name);
string destPath = Path.Combine(dirDest, file.Name);
file.CopyTo(destPath);
tw.WriteLine("Moved [{0}] to [{1}] at {2}", name, destPath, DateTime.Now);
//Console.WriteLine("Name: {0}", ((ManagementBaseObject)e["TargetInstance"])["Name"]);
//Console.WriteLine("FileName: {0}", ((ManagementBaseObject)e["TargetInstance"])["FileName"]);
// Run this bitch to discover what's available.
//ManagementBaseObject dataFile = (ManagementBaseObject)e["TargetInstance"];
//PropertyDataCollection properties = dataFile.Properties;
//foreach (PropertyData property in properties)
//{
// Console.WriteLine("{0}: {1}", property.Name, property.Value);
//}
watcher.Stop();
tw.Close();
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
示例8: Main
static void Main()
{
string query =
@"Select * From __InstanceCreationEvent " +
@"Within 1 " +
@"Where TargetInstance Isa 'Cim_DataFile' " +
@"And TargetInstance.Drive = 'C:' " +
@"And TargetInstance.Path = '\\Scripts\\'";
ManagementEventWatcher watcher =
new ManagementEventWatcher(query);
watcher.EventArrived +=
new EventArrivedEventHandler(HandleEvent);
watcher.Start();
System.Threading.Thread.Sleep(20000);
watcher.Stop();
}
示例9: Run
public static void Run()
{
WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");
ManagementEventWatcher watcher = new ManagementEventWatcher();
watcher.Query = query;
watcher.Options.Timeout = new TimeSpan(0,0,5);
Console.WriteLine("Open application (motepad.exe) to trigger an event.");
ManagementBaseObject e = watcher.WaitForNextEvent();
Console.WriteLine("Process {0} has been created, path is: {1}",
((ManagementBaseObject)e["TargetInstance"])["Name"], ((ManagementBaseObject)e["TargetInstance"])["ExecutablePath"]);
watcher.Stop();
}
示例10: Main
static void Main(string[] args)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
Console.WriteLine("Computer Name : {0}", m["csname"]);
Console.WriteLine("Windows Directory : {0}", m["WindowsDirectory"]);
Console.WriteLine("Operating System: {0}", m["Caption"]);
Console.WriteLine("Version: {0}", m["Version"]);
Console.WriteLine("Manufacturer: {0}", m["Manufacturer"]);
}
//-----------------------------------------------------------------------------------------
//Process creation event (waiting for)
WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
ManagementBaseObject e = watcher.WaitForNextEvent();
Console.WriteLine("Process {0} has been created, path is: {1}",
((ManagementBaseObject)e["TargetInstance"])["Name"],
((ManagementBaseObject)e["TargetINstance"])["ExecutablePath"]);
watcher.Stop();
//-----------------------------------------------------------------------------------------
//Responding to WMI Events with an Event Handler
ManagementEventWatcher mew = null;
EventReceiver receiver = new EventReceiver();
mew = GetWatcher(new EventArrivedEventHandler(receiver.OnEventArrived));
mew.Start();
Console.ReadKey();
mew.Stop();
}
示例11: FireMessageToWMI
public void FireMessageToWMI(string eventName, WmiEventDelegate action, string expected)
{
ManagementScope scope = new ManagementScope(@"\\." + WmiPath);
scope.Options.EnablePrivileges = true;
EventQuery eq = new EventQuery("SELECT * FROM " + eventName);
using (ManagementEventWatcher watcher = new ManagementEventWatcher(scope, eq))
{
watcher.EventArrived += new EventArrivedEventHandler(WatcherEventArrived);
watcher.Start();
action();
WaiUntilWMIEventArrives();
watcher.Stop();
}
Assert.IsTrue(this.wmiLogged);
Assert.IsTrue(this.wmiResult.IndexOf(expected) > -1);
}
示例12: Main
static void Main(string[] args)
{
ManagementObjectSearcher processorSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
foreach (ManagementObject obj in processorSearcher.Get())
{
Console.WriteLine(obj["Name"]);
Console.WriteLine("{0} / {1}", obj["CurrentClockSpeed"], obj["MaxClockSpeed"]);
}
EventQuery query = new EventQuery();
//query.QueryString = "SELECT * FROM _InstanceModifiationEvent WITHIN 3600 WHERE TargetInstance ISA 'Win32_DiskDrive'";
query.QueryString = "SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance isa \"Win32_Process\"";
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
watcher.Options.Timeout = new TimeSpan(0, 0, 30);
EventArrivedEventHandler eventArrived = new EventArrivedEventHandler(EventReceived);
watcher.EventArrived += eventArrived;
watcher.Start();
Console.WriteLine("Open an application (notepad.exe) to trigger an event.");
//ManagementBaseObject e = watcher.WaitForNextEvent();
Console.WriteLine("Actually I rewrote this to use events, it will now monitor all application starts until you hit a key...");
ConsoleKeyInfo key;
while (true)
{
key = Console.ReadKey();
if (key.KeyChar.Equals('q'))
break;
}
/*
//Display information from the event
Console.WriteLine("Process {0} has been created, path is: {1}", ((ManagementBaseObject)e["TargetInstance"])["Name"],
((ManagementBaseObject)e["TargetInstance"])["ExecutablePath"]);
*/
watcher.Stop();
}
示例13: TestLoggingAInheritedCustomEntry
public void TestLoggingAInheritedCustomEntry()
{
ManagementScope scope = new ManagementScope(@"\\." + this.wmiPath);
scope.Options.EnablePrivileges = true;
string query = "SELECT * FROM MyInheritedCustomLogEntry";
EventQuery eq = new EventQuery(query);
using (ManagementEventWatcher watcher = new ManagementEventWatcher(scope, eq))
{
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Start();
this.sink.SendMessage(GetCustomLogEntry());
BlockUntilWMIEventArrives();
watcher.Stop();
}
Assert.IsTrue(this.wmiLogged);
Assert.IsTrue(this.wmiResult.IndexOf(CommonUtil.MsgBody) > -1);
}
示例14: Main
static void Main(string[] args)
{
var scope = new ManagementScope();
scope.Path.NamespacePath = WmiConstants.Namespace;
var createdWatcher = new ManagementEventWatcher(scope, new WqlEventQuery(WmiConstants.TaskCreatedQuery));
var changedWatcher = new ManagementEventWatcher(scope, new WqlEventQuery(WmiConstants.TaskChangedQuery));
var removedWatcher = new ManagementEventWatcher(scope, new WqlEventQuery(WmiConstants.TaskRemovedQuery));
createdWatcher.EventArrived += ObjectCreated_EventArrived;
changedWatcher.EventArrived += ObjectChanged_EventArrived;
removedWatcher.EventArrived += ObjectRemoved_EventArrived;
try
{
createdWatcher.Start();
changedWatcher.Start();
removedWatcher.Start();
Console.WriteLine("Press Any Key to Exit");
Console.WriteLine();
Console.Read();
}
finally
{
if (createdWatcher != null)
createdWatcher.Stop();
if (changedWatcher != null)
changedWatcher.Stop();
if (removedWatcher != null)
removedWatcher.Stop();
}
}
示例15: ExecuteRemoteProcess
public void ExecuteRemoteProcess(string command)
{
Wmi cimv2 = new Wmi(ServerNameSettings, "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;
}
}
}