可以在WinForms中使用'DeviceWatcher'吗?

时间:2014-02-17 17:34:37

标签: c# .net vb.net visual-studio microsoft-metro

我试图在.NET Framework Classes中找到最有效且可能实现的方式来监控驱动器,实际上我知道如何使用结构等进行P /调用...但是它是很多代码而我我想改进它。

所以我发现了这个有趣的类DeviceWatcher,它似乎只适用于Metro应用程序?

我找不到关于该类的更多信息,我想知道从Winforms可能引用所需的dll我可以将此类实例化以在Winforms中使用它吗?

2 个答案:

答案 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.FoundationWindows的引用:

enter image description here

执行此操作后,您可以实例化Watcher并添加事件处理程序:

DeviceWatcher dw = Windows.Devices.Enumeration.DeviceInformation.CreateWatcher();

dw.Added += dw_Added;
dw.Removed += dw_Removed;

dw.Start();

答案 1 :(得分:0)

所以基本上这些都是正确的步骤:

  
      
  1. 创建一个面向.NET Framework 4.5的新“WinForms”项目。

  2.   
  3. 关闭VisualStudio,在文本编辑器中打开“ YourProjectName.vbproj ”文件并添加此属性:

  4.   
<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