Excel-DNA で XLL をつくる(その10)

 今回はPCに接続されたUSBメモリの履歴をレジストリから取得してExcel のシートに列挙してみます。
誰かが、あなたの PC から、こっそりデータを盗み出したりしてませんか?

(こんな感じ↓)

実行すると・・・

(こんな感じ↓)

 では、さっそく記述してみましょう。

 今回も、DLL を作成するまでもないので、.dna ファイルに直接記述します。
(Excel-DNA についてはこちらをご覧ください) Excel-DNA以外に用意するものもありません。入力した文字列の長さにフィットするようにセルの幅を変更してみますので、Excel-DNA からExcel4.0 Macro Function を呼び出す方法について理解することが出来ると思います。

(こんな感じ↓)

<DnaLibrary RuntimeVersion="v4.0" Language="CS">

<!&#91;CDATA&#91;

using System;
using Microsoft.Win32;
using ExcelDna.Integration;

public static class USBSTOR
{
    const int limit = 100;
    const string root = @"System\CurrentControlSet\Enum\USBSTOR";
    &#91;ExcelCommand(MenuName = "USB履歴", MenuText = "USB使用履歴をA,B列に表示")&#93;
    public static void GetUsbStories()
    {
        // レジストリを読み込み
        RegistryKey ParentKey = Registry.LocalMachine.OpenSubKey(root);
        string&#91;&#93; keyNames = ParentKey.GetSubKeyNames();
        int row = 0, col = 0;
        ExcelReference head_a = new ExcelReference(row, col);
        head_a.SetValue("ベンダー");
        ExcelReference head_b = new ExcelReference(row, col + 1);
        head_b.SetValue("USB_ID");
        row++;
        // ベンダーとUSB_IDをセルに表示
        foreach (string KeyName in keyNames)
        {
            ExcelReference VenderRange = new ExcelReference(row, col);
            VenderRange.SetValue(KeyName);
            string&#91;&#93; SubKeyNames = ParentKey.OpenSubKey(KeyName).GetSubKeyNames();
            foreach (string SubKeyName in SubKeyNames)
            {
                ExcelReference IDRange = new ExcelReference(row, col + 1);
                IDRange.SetValue(SubKeyName);
                row++;
            }
        }
        // 列幅をAutoFitする
        XlCall.Excel(XlCall.xlcColumnWidth, 1, new ExcelReference(0, row, 0, 1), false, 3);
    }
}

&#93;&#93;>
</DnaLibrary>
 

 「特定のUSBメモリが、あるPCに接続された事があるかどうか?」は、この方法で特定できます♪ 
不審な USB メモリが挿入されていないか定期的にチェックし、リストを保存するとUSBメモリの不正使用をもくろむ向きにプレッシャーをかけることが出来るかもしれませんね(笑)
(WMI を使う方法についてはサイトの記事 を参照してください)

では、また(笑)

ダウンロードはこちら⇒ USBStor.zip

カテゴリー: Excel, .NetFramework タグ: , パーマリンク

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です