[C#]偵測是否有卸除式存放裝置插入,使用 WndProc 方法與 DriveInfo 類別

  • 29367
  • 0
  • 2010-08-02

偵測是否有卸除式存放裝置插入,使用 WndProc 方法與 DriveInfo 類別

 

1. 問題描述

延續上一個主題 [VB.NET]偵測是否有卸除式存放裝置插入,使用 DriveInfo 類別

此文介紹使用WndProc 方法,偵測是否有卸除式存放裝置插入,並且透過 DriveInfo 類別取得磁碟資訊

對於 DriveInfo 有興趣的請參考上一篇文章,此文不再累述。

 

2. 方法

2.1 使用方法介紹

WndProc 用來處理 Windows 訊息。在這裡,我們使用到三個訊息

WM_DEVICECHANGE Message : 電腦硬體裝置改變時產生的訊息

DBT_DEVICEARRIVAL Event : 裝置插入並且可以使用時,產生的系統訊息

DBT_DEVICEREMOVECOMPLETE Event : 裝置卸載或移除時產生的系統訊息

 

2.2 程式碼


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApplication10
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_DEVICECHANGE = 0x219;
            const int DBT_DEVICEARRIVAL = 0x8000;
            const int DBT_DEVICEREMOVECOMPLETE = 0x8004;

            object ojb = new object();
            try
            {
                // WM_DEVICECHANGE Message : 電腦硬體裝置改變時產生的訊息
                if (m.Msg == WM_DEVICECHANGE)
                {
                    switch (m.WParam.ToInt32())
                    {
                        case WM_DEVICECHANGE:
                            break;
                        // DBT_DEVICEARRIVAL Event : 裝置插入並且可以使用時,產生的系統訊息
                        case DBT_DEVICEARRIVAL:
                        // DBT_DEVICEREMOVECOMPLETE Event : 裝置卸載或移除時產生的系統訊息
                        case DBT_DEVICEREMOVECOMPLETE:
                            DeviceChange();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            base.WndProc(ref m);
        }

        private void DeviceChange()
        {
            listBox1.Items.Clear();
            foreach (DriveInfo di in DriveInfo.GetDrives())
            {
                if (di.DriveType == DriveType.Removable)
                {
                    listBox1.Items.Add("偵測到" + di.Name + "抽取式存放裝置");
                }
            }

        }
    }
}

 

2.3 執行結果

插入抽取式存放裝置時

image

拔除抽取式存放裝置時

image

 

2.4 範例下載

C# CSharpDetectDisk.rar

VB.NET VBDetectDisk.rar