我正在學習C#,我需要幫助。 我的問題:如何知道USB磁盤是否已安裝/未安裝? 我找到了答案WndProd監控一個端口的USB,沒有WinForm,只有控制檯應用程序
const int WM_DEVICECHANGE = 0x0219;
const int DBT_DEVICEARRIVAL = 0x8000;
const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
[StructLayout(LayoutKind.Sequential)]
public struct DEV_BROADCAST_HDR
{
public int dbch_size;
public int dbch_devicetype;
public int dbch_reserved;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_DEVICECHANGE)
{
int EventCode = m.WParam.ToInt32();
Log(string.Format("WM_DEVICECHANGE. Код={0}", EventCode));
switch (EventCode)
{
case DBT_DEVICEARRIVAL:
{
Log("Добавление устройства");
break;
}
case DBT_DEVICEREMOVECOMPLETE:
{
Log("Удаление устройства");
break;
}
}
}
base.WndProc (ref m);
}
這個版本
public class WMIReceiveEvent
{
public WMIReceiveEvent()
{
try
{
WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
Console.WriteLine("Waiting for an event...");
watcher.EventArrived += new EventArrivedEventHandler(HandleEvent);
// Start listening for events
watcher.Start();
// Do something while waiting for events
System.Threading.Thread.Sleep(20000);
// Stop listening for events
//watcher.Stop();
//return;
}
catch (ManagementException err)
{
}
}
private void HandleEvent(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("Win32_DeviceChangeEvent event occurred. "+ e.NewEvent.ClassPath.ClassName.ToString());
Console.WriteLine("2_Win32_DeviceChangeEvent event occurred. " + e.NewEvent.Properties.ToString());
Console.ReadLine();
}
}
但我想版本DBT_DEVICEARRIVAL和DBT_DEVICEREMOVECOMPLETE沒有WinForm的。因爲對於WndProc需要System.Windows.Form和Class必須是繼承人「:表格」 而對於WMIReceiveEvent不是我的任務的最佳解決方案。
非常感謝您的快速響應。以及如何自己寫一個消息循環?或如何在ConsoleApp中使用「背景」應用程序(如果它是後續的「:Form」)?謝謝 – 2012-03-08 08:47:57