* C# WMI 를 이용한 USB 연결 및 연결해제 예제...
- WMI 를 사용하기 위해 참조 -> System.Management dll 을 추가 -> 소스 코드 using System.Management
- 사용한 컨트롤 : ListView 1개, Button 2개
전체 소스 코드
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
namespace CSharp_WMI_USB_Detect
{
public partial class Form1 : Form
{
ManagementEventWatcher mewWatcher;
string strUSBDriveName;
string strUSBDriveLetter;
int iCount = 0;
public Form1()
{
InitializeComponent();
//크로스 스레드
CheckForIllegalCrossThreadCalls = false;
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (mewWatcher != null)
{
mewWatcher.Stop();
mewWatcher.Dispose();
}
}
void mewWatcher_EventArrived(object sender, System.Management.EventArrivedEventArgs e)
{
ManagementBaseObject mbo1;
ManagementBaseObject mbo2;
mbo1 = e.NewEvent as ManagementBaseObject;
mbo2 = mbo1["TargetInstance"] as ManagementBaseObject;
switch (mbo1.ClassPath.ClassName)
{
case "__InstanceCreationEvent":
{
if (mbo2["InterfaceType"].ToString() == "USB")
{
strUSBDriveName = mbo2["Caption"].ToString();
strUSBDriveLetter = mbo2["Name"].ToString();
ListViewItem lvi = new ListViewItem();
lvi.Text = (iCount + 1).ToString();
lvi.SubItems.Add(strUSBDriveName + " : " + strUSBDriveLetter + " 연결 되었습니다.");
listView1.Items.Add(lvi);
iCount += 1;
}
break;
}
case "__InstanceDeletionEvent":
{
if (mbo2["InterfaceType"].ToString() == "USB")
{
if (mbo2["Caption"].ToString() == strUSBDriveName)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = (iCount + 1).ToString();
lvi.SubItems.Add(strUSBDriveName + " : " + strUSBDriveLetter + " 해제 되었습니다.");
listView1.Items.Add(lvi);
iCount += 1;
strUSBDriveLetter = "";
strUSBDriveName = "";
}
}
break;
}
}
this.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
//start
//ManageMentEventWatcher 가 null 이면 생성...
if (mewWatcher == null) mewWatcher = new ManagementEventWatcher();
WqlEventQuery weQuery = new WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 1 " + "WHERE TargetInstance ISA 'Win32_DiskDrive'");
mewWatcher.Query = weQuery;
//Event Create
mewWatcher.EventArrived += new EventArrivedEventHandler(mewWatcher_EventArrived);
mewWatcher.Start();
}
private void button2_Click(object sender, EventArgs e)
{
//stop
mewWatcher.Stop();
mewWatcher.Dispose();
}
}
}
위 구문에서 보듯이 CheckfoCheckForIllegalCrossThreadCalls 를 사용 (크로스 스레드 예제 https://kdsoft-zeros.tistory.com/22 참조)
- 아래 클래스에 붉은색 표시 -> 소스코드에 사용한 필드 !!
[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/182
'C# Programming' 카테고리의 다른 글
[C#] 화면 캡쳐 (Screen Capture) (0) | 2020.04.09 |
---|---|
[C#] [Control] WebBrowser 컨트롤 - 외부 IP 알아내기 (0) | 2020.04.07 |
[C#] [WMI] CPU 클럭 속도 (CurrentClockSpeed) (0) | 2020.04.01 |
[C#] 파일 비교 (File Compare) (0) | 2020.03.30 |
[C#] DateTimeFormat - 전역 설정 (0) | 2020.03.25 |