gpt4 book ai didi

c# - 在 C# 中检测 USB 设备的插入和移除

转载 作者:行者123 更新时间:2023-11-30 18:27:17 30 4
gpt4 key购买 nike

我尝试了此线程中的一种解决方案 Detecting USB drive insertion and removal using windows service and c# .但由于对 Windows 窗体控件的线程不安全调用,我仍然遇到错误。

这是我的代码

private void initWatchers()
{

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();

}

在事件处理程序中我启动了 backgroundworker

private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}
void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}

backgroundworker 完成后,我确实访问了 windows 窗体中的控件

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// access some controls of my windows form
}

所以现在我仍然会因为控件的不安全调用而出错。知道为什么吗?

最佳答案

这是因为 GUI 元素位于应用程序的 GUI 线程中,而您正试图从 BackGroundWorker 线程访问它们。您必须使用委托(delegate)来处理 BackgroundWorker 中的 GUI 元素。例如:

    GUIobject.Dispatcher.BeginInvoke(
(Action)(() => { string value = myTextBox.Text; }));

在 RunWorkerCompleted 上,您仍在尝试从 BackGroundWorker 访问 GUI 元素。

关于c# - 在 C# 中检测 USB 设备的插入和移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26975946/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com