方法1:
//USB裝置感應子產品(應用底層較為代碼)
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x219)
{
if (m.WParam.ToInt32() == 0x8000)
{
DriveInfo[] allDrivers = DriveInfo.GetDrives();
foreach (var d in allDrivers) // 系統會自動掃描包含C:\\ 之類的,以及我們插入的U盤和移動硬碟
{
if (allDrivers[i].IsReady)
if (d.IsReady)
{
if (allDrivers[i].DriveType == DriveType.Removable) //查找到的是移動式的 磁盤
{
//(在這裡填寫你需處理的代碼)
DialogResult dr = MessageBox.Show("是否要拷貝U盤中的資訊?", "U盤", MessageBoxButtons.OKCancel);
if (dr == DialogResult.OK)
{
MessageBox.Show("正在搜尋U盤中資料,請稍後~");
}
}
}
}
}
}
base.WndProc(ref m);
方法二:使用C#方法 (使用一個定時器)
private void timer1_Tick(object sender, EventArgs e)
{
DriveInfo[] allDrivers = DriveInfo.GetDrives();
foreach (var d in allDrivers)
{
if (d.IsReady)
{
if (d.DriveType == DriveType.Removable)
{
string[] filenames = Directory.GetFileSystemEntries(d.Name);
foreach (string file in filenames) //依次通路該磁盤中的檔案或檔案夾
{
if (Path.GetFileName(file) == "office") //判斷該移動磁盤中是否有某個檔案夾或檔案
{
this.timer1.Enabled = false //暫時關閉定時器
DialogResult dr = MessageBox.Show("是否要拷貝U盤中的資訊?", "U盤", MessageBoxButtons.OKCancel);
if (dr == DialogResult.OK)
{
//MessageBox.Show("正在搜尋U盤中資料,請稍後~");
this.label1.Text = "磁盤位置:" + d.Name;
}
break;
}
}
}
}
}
}
this.timer1.Enabled = true; //開啟定時器
}