반응형

* VBNET WMI 를 이용한 USB 연결 및 연결해제 예제...

- WMI 를 사용하기 위해 참조 -> System.Management dll 을 추가 -> 소스 코드 Imports System.Management


Main


- 사용한 컨트롤 : ListView 1개, Button 2개

 

전체 소스 코드

Form1.vb

 

Imports System.Management

Public Class Form1

    Dim mewWatcher As ManagementEventWatcher
    Dim strUSBDriveName As String
    Dim strUSBDriveLetter As String
    Dim iCount As Integer = 0

    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        MyBase.OnLoad(e)

        CheckForIllegalCrossThreadCalls = False

    End Sub

    Protected Overrides Sub OnClosed(ByVal e As System.EventArgs)
        MyBase.OnClosed(e)

        If Not mewWatcher Is Nothing Then

            mewWatcher.Stop()
            mewWatcher.Dispose()

        End If

    End Sub

    Sub mewWatcher_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs)

        Dim mbo1 As ManagementBaseObject
        Dim mbo2 As ManagementBaseObject

        mbo1 = CType(e.NewEvent, ManagementBaseObject)
        mbo2 = CType(mbo1("TargetInstance"), ManagementBaseObject)

        Select Case mbo1.ClassPath.ClassName

            Case "__InstanceCreationEvent"

                If mbo2("InterfaceType").ToString() = "USB" Then
                    strUSBDriveName = mbo2("Caption").ToString()
                    strUSBDriveLetter = mbo2("Name").ToString()

                    Dim lvi As ListViewItem = New ListViewItem()
                    lvi.Text = (iCount + 1).ToString()
                    lvi.SubItems.Add(strUSBDriveName + " : " + strUSBDriveLetter + " 연결 되었습니다.")

                    listView1.Items.Add(lvi)
                    iCount += 1
                End If

            Case "__InstanceDeletionEvent"

                If mbo2("InterfaceType").ToString() = "USB" Then
                    If mbo2("Caption").ToString() = strUSBDriveName Then
                        Dim lvi As ListViewItem = New ListViewItem()
                        lvi.Text = (iCount + 1).ToString()
                        lvi.SubItems.Add(strUSBDriveName + " : " + strUSBDriveLetter + " 해제 되었습니다.")

                        listView1.Items.Add(lvi)
                        iCount += 1

                        strUSBDriveLetter = ""
                        strUSBDriveName = ""
                    End If
                End If
        End Select


    End Sub


    Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
        'Start
        'ManageMentEventWatcher 가 null 이면 생성...
        If mewWatcher Is Nothing Then mewWatcher = New ManagementEventWatcher()

        Dim weQuery As WqlEventQuery = New WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " + "WHERE TargetInstance ISA 'Win32_DiskDrive'")
        mewWatcher.Query = weQuery
        'Event Create
        AddHandler mewWatcher.EventArrived, AddressOf mewWatcher_EventArrived
        mewWatcher.Start()

    End Sub

    Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click
        'Stop
        If mewWatcher Is Nothing Then Return

        mewWatcher.Stop()
        mewWatcher.Dispose()
    End Sub

End Class

 

위 구문에서 보듯이 CheckfoCheckForIllegalCrossThreadCalls 를 사용 (크로스 스레드 예제 https://kdsoft-zeros.tistory.com/23 참조)

 

- 아래 클래스에 붉은색 표시 -> 소스코드에 사용한 필드 !!

 

[Dynamic, Provider("CIMWin32"), UUID("{8502C4B2-5FBB-11D2-AAC1-006008C78BC7}"), AMENDMENT]
class Win32_DiskDrive : CIM_DiskDrive
{
  uint16   Availability;
  uint32   BytesPerSector;
  uint16   Capabilities[];
  string   CapabilityDescriptions[];
  string   Caption;
  string   CompressionMethod;
  uint32   ConfigManagerErrorCode;
  boolean  ConfigManagerUserConfig;
  string   CreationClassName;
  uint64   DefaultBlockSize;
  string   Description;
  string   DeviceID;
  boolean  ErrorCleared;
  string   ErrorDescription;
  string   ErrorMethodology;
  string   FirmwareRevision;
  uint32   Index;
  datetime InstallDate;
  string   InterfaceType;
  uint32   LastErrorCode;
  string   Manufacturer;
  uint64   MaxBlockSize;
  uint64   MaxMediaSize;
  boolean  MediaLoaded;
  string   MediaType;
  uint64   MinBlockSize;
  string   Model;
  string   Name;
  boolean  NeedsCleaning;
  uint32   NumberOfMediaSupported;
  uint32   Partitions;
  string   PNPDeviceID;
  uint16   PowerManagementCapabilities[];
  boolean  PowerManagementSupported;
  uint32   SCSIBus;
  uint16   SCSILogicalUnit;
  uint16   SCSIPort;
  uint16   SCSITargetId;
  uint32   SectorsPerTrack;
  string   SerialNumber;
  uint32   Signature;
  uint64   Size;
  string   Status;
  uint16   StatusInfo;
  string   SystemCreationClassName;
  string   SystemName;
  uint64   TotalCylinders;
  uint32   TotalHeads;
  uint64   TotalSectors;
  uint64   TotalTracks;
  uint32   TracksPerCylinder;
};

 

*예제 결과

 

- 연결된 모습

 

-연결 해제된 모습

 

* 참조 (마이크로소프트)

https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-diskdrive



https://kdsoft-zeros.tistory.com/181

 

[C#] [WMI] USB Detect 예제

* C# WMI 를 이용한 USB 연결 및 연결해제 예제... - WMI 를 사용하기 위해 참조 -> System.Management dll 을 추가 -> 소스 코드 using System.Management - 사용한 컨트롤 : ListView 1개, Button 2개 전체 소..

kdsoft-zeros.tistory.com

 

반응형

+ Recent posts