可以在WinForms中使用’DeviceWatcher’吗?
我试图在.NET Framework类中找到最有效和可能实现的方法来监控驱动器,实际上我知道如何使用结构等进行P /调用…但是它是很多代码我希望改进它。
所以我发现这个有趣的Class, DeviceWatcher ,它似乎只适用于Metro应用程序?
我找不到关于该类的更多信息,我想知道如果从Winforms可能引用所需的dll我可以实例这个类在Winforms中使用它吗?
是的,如果你在Win 8 / Win Server 2012上运行,它是可能的。
Scott Hanselman有一篇关于如何从桌面应用程序调用WinRT方法的好文章 。
它的基础是,将以下内容添加到项目文件中(卸载,编辑,重新加载):
8.0
然后添加对C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades\System.Runtime.InteropServices.WindowsRuntime.dll
您还需要通过Windows
选项卡下的“添加引用”对话框添加对Windows.Devices
和Windows.Foundation
的引用:
完成后,您可以实例化Watcher并添加事件处理程序:
DeviceWatcher dw = Windows.Devices.Enumeration.DeviceInformation.CreateWatcher(); dw.Added += dw_Added; dw.Removed += dw_Removed; dw.Start();
所以基本上这些都是正确的步骤:
创建一个面向.NET Framework 4.5的新“WinForms”项目。
关闭VisualStudio,在文本编辑器中打开“ YourProjectName.vbproj ”文件并添加以下属性:
... 8.0 ...
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>核心 ”选项卡并添加以下参考:
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