我试图在.NET Framework Classes中找到最有效且可能实现的方式来监控驱动器,实际上我知道如何使用结构等进行P /调用...但是它是很多代码而我我想改进它。
所以我发现了这个有趣的类DeviceWatcher,它似乎只适用于Metro应用程序?
我找不到关于该类的更多信息,我想知道从Winforms可能引用所需的dll我可以将此类实例化以在Winforms中使用它吗?
答案 0 :(得分:4)
是的,如果你在Win 8 / Win Server 2012上运行,它是可能的。
Scott Hanselman对于如何从桌面应用程序调用WinRT方法有一个很好的article。
它的基础是,将以下内容添加到项目文件中(卸载,编辑,重新加载):
<PropertyGroup>
<TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>
然后添加对C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades\System.Runtime.InteropServices.WindowsRuntime.dll
您还需要通过Windows.Devices
标签下的“添加引用”对话框添加对Windows.Foundation
和Windows
的引用:
执行此操作后,您可以实例化Watcher并添加事件处理程序:
DeviceWatcher dw = Windows.Devices.Enumeration.DeviceInformation.CreateWatcher();
dw.Added += dw_Added;
dw.Removed += dw_Removed;
dw.Start();
答案 1 :(得分:0)
所以基本上这些都是正确的步骤:
创建一个面向.NET Framework 4.5的新“WinForms”项目。
- 醇>
关闭VisualStudio,在文本编辑器中打开“ YourProjectName.vbproj ”文件并添加此属性:
<PropertyGroup>
...
<TargetPlatformVersion>8.0</TargetPlatformVersion>
...
</PropertyGroup>
3.在VisualStudio中加载项目,打开“参考”菜单并添加以下参考:
C:\ Program Files(x86)\ Reference Assemblies \ Microsoft \ Framework.NETFramework \ v4.5 \ Facades \ System.Runtime.dll
C:\ Program Files(x86)\ Reference Assemblies \ Microsoft \ Framework.NETFramework \ v4.5 \ Facades \ System.Runtime.InteropServices.WindowsRuntime.dll
4.在“参考”菜单中,转到“ Windows&gt; Core ”标签并添加以下参考:
<强> Windows.Devices 强>
<强> Windows.Foundation 强>
现在您将能够执行此操作:
Public Class DeviceWatcher_Test
Private WithEvents dw As DeviceWatcher = DeviceInformation.CreateWatcher()
Private Sub Test() Handles MyBase.Load
dw.Start()
End Sub
Private Sub dw_Added(ByVal sender As DeviceWatcher, ByVal e As DeviceInformation) _
Handles dw.Added
Debug.WriteLine("dw_added: " & e.Id & " | " & e.Name)
End Sub
Private Sub dw_Removed(ByVal sender As DeviceWatcher, ByVal e As DeviceInformationUpdate) _
Handles dw.Removed
Debug.WriteLine("dw_Removed: " & e.Id)
End Sub
Private Sub dw_Updated(ByVal sender As DeviceWatcher, ByVal e As DeviceInformationUpdate) _
Handles dw.Updated
Debug.WriteLine("dw_Updated: " & e.Id)
End Sub
Private Sub dw_Stopped(ByVal sender As DeviceWatcher, ByVal e As Object) _
Handles dw.Stopped
Debug.WriteLine("dw_Stopped: " & e.ToString)
End Sub
Private Sub dw_EnumerationCompleted(ByVal sender As DeviceWatcher, ByVal e As Object) _
Handles dw.EnumerationCompleted
Debug.WriteLine("dw_EnumerationCompleted: " & e.ToString)
End Sub
End Class