C#實現文件拖放並打開文件


 

C#實現文件拖放並打開文件

需要知道的ListBox的兩個事件:當您在控件的邊界內拖動對象時,便會發生 DragEnter 事件;該事件用於確

定當前拖動的對象是不是您要放到控件上的對象。 在將一個或多個文件拖到控件上時,需要處理此事件。 這使

得在將對象拖到控件上方時,能夠根據所拖動的對象顯示相應的圖標。 將拖動的對象釋放到控件上時,會發生

DragDrop 事件。

功能描述:向ListBox拖入一個文件,ListBox顯示該文件的路徑,然后單擊該路徑,點擊Open按鈕打開該文件。

 

代碼實現:

需要將ListBox的AllowDrop屬性改為true,並實現它的DragEnterDragDrop這兩個事件。

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

namespace DragDrop
{
    public partial class DragDrop : Form
    {
        public string FilePath;

        public DragDrop()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 獲取ListBox的值。
        /// </summary>
        /// <returns></returns>
        public string GetListBoxItem()
        {
            string filePath = string.Empty;
            
            bool isSelected = IsListBoxSelected();

            if (isSelected==true)
            {
                string listBoxItemValue = lbFilePath.SelectedItem.ToString();

                filePath = listBoxItemValue;
            }
            else
            {
                MessageBox.Show("ListBox must be selected.");
            }

            return filePath;
        }

        /// <summary>
        /// ListBox內的值是否被選中。
        /// </summary>
        /// <returns></returns>
        public bool IsListBoxSelected()
        {
            bool selected;

            if (lbFilePath.SelectedIndex == -1)//SelectedIndex==-1時,表示未選中任何項。
            {
                selected = false;
            }
            else
            {
                selected = true;
            }

            return selected;
        }

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

        private void lbFilePath_DragDrop(object sender, DragEventArgs e)
        {
            string[] s=(string[])e.Data.GetData(DataFormats.FileDrop,false);
            
            for (int i = 0; i < s.Length; i++)
            {
                lbFilePath.Items.Add(s[i]);
            }
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            string filePath=GetListBoxItem();

            if (!string.IsNullOrEmpty(filePath))
            {
                System.Diagnostics.Process.Start(filePath);
            }
        }
    }
}

 

總結:

Data 對象的 GetData 方法返回一個字符串數組,該數組包含拖到該列表框控件中的文件的完整路徑名。 可以使用此文件路徑信息來執行需要對文件執行的任何操作。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM