2017年10月17日火曜日

drag and dropとLixt Box

Listboxにドラッグ & ドロップしたファイルを表示してみます。

以下をformに配置します。
picturebox : 画像表示用
textbox x 3 : ディレクトリ名表示・ファイル名表示・画像サイズ表示 (表示するだけなのでlabelでも可です)
listbox : ドラッグ & ドロップはこちらに対して行います

listboxにファイルをドラッグ & ドロップするとアイテムが増え、listboxのアイテムを選択する事でtextboxへの(大した事ない)情報表示と、pictureboxの画像が切り替わります。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;        // file / directory文字列処理など
using OpenCvSharp;   // 今回はNuGetでOpenCV sharp 3を導入(2が見つからなくなっていたので)
using OpenCvSharp.Extensions;  // bitmap converterの為

namespace DragDrop01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            listBox1.AllowDrop = true;      // プロパティを編集してもよい(やらないとEnterイベントが発生しない模様)
        }

        private void listBox1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            } else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void listBox1_DragDrop(object sender, DragEventArgs e)
        {
            string[] fileName = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            listBox1.Items.AddRange(fileName);
        }

        // listboxの選択変更
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string currentItem = listBox1.SelectedItem.ToString();  // アイテムを取得する

            // int index = listBox1.FindString(currentItem);           // (↑のアイテムから)indexを取得する事も可

            textBox1.Text = Path.GetDirectoryName(currentItem);
            textBox2.Text = Path.GetFileName(currentItem);

            Mat image = new Mat(currentItem);
            string imageSize = image.Width.ToString() + " : " + image.Height.ToString();
            textBox3.Text = imageSize.ToString();

            Cv2.Resize(image, image, new OpenCvSharp.Size(pictureBox1.Width, pictureBox1.Height));
            pictureBox1.Image = BitmapConverter.ToBitmap(image);
        }
    }
}

0 件のコメント:

コメントを投稿