Handler

C# で作成した File Handler の原型です。

前田稔(Maeda Minoru)の超初心者のプログラム入門

プログラムの説明

  1. TreeView にはドライブ一覧を検索して、アイコンを設定して表示します。
    ListView にはデスクトップを検索して、アイコンを設定して表示します。
    TreeView の+をクリックするとツリーが展開します。
    TreeView のノード(フォルダー)をクリックすると ListView に一覧が表示されます。
  2. CLI の環境で実行可能な完成したプログラムです。
    事前に "C:\\DATA\\Test\\" に6個のアイコンファイルを格納しておいて下さい。
    アイコン画像の取得と説明は Drive Icon を参照して下さい。
    実行の方法は Command Line から Windows プログラムを実行 を参照して下さい。
    /*************************************************/
    /*★ Handler Tree & List の基本設定    前田 稔 ★*/
    /*************************************************/
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using System.IO;
    using System.Management;
    
    public class MyForm : Form
    {
        private     SplitContainer splitContainer1;
        private     TreeView treeView1;
        private     ListView listView1;
        int[]       width = { 320, 120, 80, 40 };
        string[]    head = { "名前", "更新日付", "サイズ", "種類" };
        ImageList   imageListSmall = new ImageList();
        string[]    iconFiles =
        { "C:\\DATA\\Test\\null.ico", "C:\\DATA\\Test\\folder.ico",
          "C:\\DATA\\Test\\fdd.ico", "C:\\DATA\\Test\\hdd.ico",
          "C:\\DATA\\Test\\cd.ico", "C:\\DATA\\Test\\remove.ico"
        };
        public string   Sel_Dir = "";
    
        public MyForm()
        {   InitializeComponent();
            Load += new System.EventHandler(MyForm_Load);
        }
    
        private void InitializeComponent()
        {
            this.splitContainer1 = new System.Windows.Forms.SplitContainer();
            this.treeView1 = new System.Windows.Forms.TreeView();
            this.listView1 = new System.Windows.Forms.ListView();
            this.splitContainer1.Panel1.SuspendLayout();
            this.splitContainer1.Panel2.SuspendLayout();
            this.splitContainer1.SuspendLayout();
            this.SuspendLayout();
            // splitContainer1
            this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splitContainer1.Location = new System.Drawing.Point(0, 0);
            this.splitContainer1.Name = "splitContainer1";
            // splitContainer1.Panel1
            this.splitContainer1.Panel1.Controls.Add(this.treeView1);
            // splitContainer1.Panel2
            this.splitContainer1.Panel2.Controls.Add(this.listView1);
            this.splitContainer1.Size = new System.Drawing.Size(764, 400);
            this.splitContainer1.SplitterDistance = 195;
            this.splitContainer1.TabIndex = 0;
            // treeView1
            this.treeView1.BackColor = System.Drawing.SystemColors.ControlLightLight;
            this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.treeView1.Location = new System.Drawing.Point(0, 0);
            this.treeView1.Name = "treeView1";
            this.treeView1.Size = new System.Drawing.Size(195, 400);
            this.treeView1.TabIndex = 0;
            this.treeView1.BeforeExpand +=
                new System.Windows.Forms.TreeViewCancelEventHandler(this.treeView1_BeforeExpand);
            this.treeView1.AfterSelect +=
                new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
            // listView1
            this.listView1.BackColor = System.Drawing.SystemColors.ControlLight;
            this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.listView1.FullRowSelect = true;
            this.listView1.GridLines = true;
            this.listView1.Location = new System.Drawing.Point(0, 0);
            this.listView1.Name = "listView1";
            this.listView1.Size = new System.Drawing.Size(565, 400);
            this.listView1.TabIndex = 0;
            this.listView1.UseCompatibleStateImageBehavior = false;
            this.listView1.View = System.Windows.Forms.View.Details;
            // MyForm
            this.ClientSize = new System.Drawing.Size(764, 400);
            this.Controls.Add(this.splitContainer1);
            this.Name = "MyForm";
            this.splitContainer1.Panel1.ResumeLayout(false);
            this.splitContainer1.Panel2.ResumeLayout(false);
            this.splitContainer1.ResumeLayout(false);
            this.ResumeLayout(false);
        }
    
        // アプリケーションの初期化
        private void MyForm_Load(object sender, System.EventArgs e)
        {
            //List View にカラムを設定
            ColumnHeader[] columnHead = new ColumnHeader[width.GetLength(0)];
            for (int i=0; i<width.GetLength(0); i++)
            {   columnHead[i] = new ColumnHeader();
                columnHead[i].Width = width[i];
                columnHead[i].Text = head[i];
            }
            listView1.Columns.AddRange(columnHead);
    
            //ImageList の作成
            imageListSmall.ImageSize = new Size(16, 16);
            listView1.SmallImageList = imageListSmall;
            treeView1.ImageList = imageListSmall;
    
            imageListSmall.Images.Clear();
            for (int i = 0; i < iconFiles.GetLength(0); i++)
            { imageListSmall.Images.Add(new Bitmap(iconFiles[i])); }
    
            //Tree にマイコンピュータとドライブ一覧を登録
            treeView1.Nodes.Clear();
            TreeNodeEx tne = new TreeNodeEx("マイ コンピュータ");
    
            string[] drives = Directory.GetLogicalDrives();
            foreach (string drive in drives) 
            {
                string drive2 = drive.Substring(0, 2);  // 先頭2文字(C:)
                ManagementObject disk =
                    new ManagementObject("win32_logicaldisk.deviceid=\"" + drive2 + "\"");
                disk.Get();
    
                TreeNodeEx tn = new TreeNodeEx(drive);
                if (drive2=="A:")
                    tn.ImageIndex = tn.SelectedImageIndex = 2;
                else  if (disk["DriveType"].ToString()=="3")
                    tn.ImageIndex = tn.SelectedImageIndex = 3;
                else  if (disk["DriveType"].ToString()=="5")
                    tn.ImageIndex = tn.SelectedImageIndex = 4;
                else  if (disk["DriveType"].ToString()=="2")
                    tn.ImageIndex = tn.SelectedImageIndex = 5;
                else
                    tn.ImageIndex = tn.SelectedImageIndex = 1;
                tne.Nodes.Add(tn);
            }
            tne.SubFoldersAdded = true;
            treeView1.Nodes.Add(tne);
            treeView1.TopNode.Expand();
        }
    
        // List View にノード(Item)を設定
        private void SetList(string path)
        {
            if (!Directory.Exists(path))    // ディレクトリが存在しない
            {   MessageBox.Show(path + " にメディアを挿入してください。");
                return;
            }
    
            listView1.Items.Clear();
            DirectoryInfo di = new DirectoryInfo(path);     //パスを指定
            string[] item = new string[4];
    
            try
            {
                //ディレクトリ一覧の取得
                DirectoryInfo[] dis = di.GetDirectories("*.*"); //パターンを指定
                for (int i = 0; i < dis.Length; i++)
                {   item[0] = dis[i].Name;
                    item[1] = dis[i].LastWriteTime.ToString();
                    item[2] = "";
                    item[3] = "";
                    listView1.Items.Add(new ListViewItem(item));
                    listView1.Items[i].ImageIndex = 1;
                }
    
                //List にファイル一覧を登録
                FileInfo [] fis = di.GetFiles("*.*");
                for(int i=0; i<fis.Length; i++)
                {   item[0] = fis[i].Name;
                    item[1] = fis[i].LastWriteTime.ToString();
                    item[2] = fis[i].Length.ToString();
                    item[3] = fis[i].Extension;
                    listView1.Items.Add(new ListViewItem(item));
    
                    Icon appIcon = System.Drawing.Icon.ExtractAssociatedIcon(fis[i].FullName);
                    listView1.Items[listView1.Items.Count-1].ImageIndex = imageListSmall.Images.Count;
                    imageListSmall.Images.Add(appIcon);
                }
            }
            catch(Exception)
            {   Console.WriteLine("アクセス権 or ERROR: " + path);  }
        }
    
        // SubFoldersAdded == false のノードを展開
        // 1つ下の階層のすべてのノードに対して、子ノードが追加済みでない場合それを追加します。
        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            TreeNodeEx node = (TreeNodeEx)e.Node;
            foreach (TreeNodeEx child in node.Nodes)
            {
                if (child.SubFoldersAdded == false)
                {
                    string path = GetPathFromNode(child);
                    try
                    {
                        DirectoryInfo di = new DirectoryInfo(path);
                        if(di.Exists)
                        {
                            DirectoryInfo[] dirs = di.GetDirectories();
                            foreach (DirectoryInfo dir in dirs) 
                            {
                                TreeNodeEx nd = new TreeNodeEx(dir.Name);
                                nd.ImageIndex         = 1 ;     // 閉じたフォルダアイコン
                                nd.SelectedImageIndex = 1 ;     // 開いたフォルダアイコン
                                child.Nodes.Add(nd);
                            }
                            child.SubFoldersAdded = true;
                        }
                    }
                    catch(Exception)
                    {   }
                }
            } 
        } 
    
        // Tree View の選択が変更された時の処理
        private void treeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
        {
            if (Sel_Dir==string.Empty)
                Sel_Dir = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            else    Sel_Dir = GetPathFromNode(e.Node);
            SetList(Sel_Dir);
            if (listView1.Items.Count >= 1)     //ListView に focus する
            {   listView1.Items[0].Selected = true ;
                listView1.Items[0].Focused  = true ;
            }
        }
    
        // ノードからパスを取得します。
        private string GetPathFromNode(TreeNode node)
        {
            if (node.Parent == null)
            {   return node.Text;   }
            return Path.Combine(GetPathFromNode(node.Parent), node.Text);
        }
    }
    
    // サブフォルダーフラグを使った TreeNodeEx
    public class TreeNodeEx : System.Windows.Forms.TreeNode
    {
        private bool isSubFoldersAdded;
    
        public TreeNodeEx(string text) : base(text)
        {   InitializeComponent();  }
    
        private void InitializeComponent()
        {   isSubFoldersAdded = false;  }
    
        public bool SubFoldersAdded
        {
            get
            {   return isSubFoldersAdded;   }
            set
            {   isSubFoldersAdded = value;  }
        }
    } 
    
    class form01
    {
        public static void Main()
        {
            MyForm mf = new MyForm();
            Application.Run(mf);
        }
    }
    
  3. Desktop の検索は ListView Directory Icon を参照して下さい。
    SetList() がフォルダーを検索して ListView に Item を設定するメソッドです。
    treeView1_BeforeExpand() が Tree のノードを展開するメソッドです。
    treeView1_AfterSelect() が Tree View の選択が変更された時のメソッドです。
    プログラムが解り易いように、メニューやツールバーは省略しています。

Handler を作成

このプログラムをベースに本格的に File Handler の開発に取り掛かります。
  1. File Handler 開発の、おおまかな作業手順に付いて説明しておきましょう。
    メニューとツールバーを配置して、レイアウトを整えます。
    先に SplitContainer を張り付けるとフォームが重なるので、ツールバーを配置してから貼り付けます。
  2. ListView のアイテムのダブルクリックでアプリケーションを起動します。
    方法が解れば、この実装は非常に簡単です。
    ダブルクリックの検出は ListView Item 選択 を参照して下さい。
    アプリケーションの起動は アプリケーションを起動する を参照して下さい。
  3. マウスの右クリックで、ListView から選択された複数のアイテムをクリップボードに記録します。
    クリップボードに記録するとエクスプローラとの連携が取れるようになります。
  4. プログラムメニューとツールバーの機能を設定します。
    メニューの設定は ToolBox からメニューを貼り付ける を参照して下さい。
  5. マウスの右クリックで表示される ContexMenu を設定します。
    ContexMenu の説明は ContextMenu(右クリックメニュー)を設定する を参照して下さい。
  6. ContexMenu が設定されると、一応骨格の完成です。
    後は用途に応じて、Menu や ContexMenu に機能を追加するだけです。

[Next Chapter ↓] File Handler
[Previous Chapter ↑] FolderView

超初心者のプログラム入門(C# Frame Work)