Winform中實現向窗體中拖放照片並顯示以及拖放文件夾顯示樹形結構(附代碼下載)

場景

向窗體中拖拽照片並顯示效果

 

 

向窗體中拖拽文件夾並顯示樹形結構效果

 

 

注:編程

博客主頁:
https://blog.csdn.net/badao_liumang_qizhi
關注公衆號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。 this

實現

新建一個窗體,在窗體中拖拽一個Panel控件,再在Panel控件上拖拽一個TreeView,而後再新增一個右鍵控件,添加兩個選項-拖放照片和拖放文件夾。spa

 

 

並分別設置兩個鼠標右鍵選項的Tag屬性分別爲1和2。.net

Form1.Designer.cs代碼

private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.panel_face = new System.Windows.Forms.Panel();
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.Tool_Ima = new System.Windows.Forms.ToolStripMenuItem();
            this.Tool_File = new System.Windows.Forms.ToolStripMenuItem();
            this.treeView1 = new System.Windows.Forms.TreeView();
            this.panel_face.SuspendLayout();
            this.contextMenuStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // panel_face
            // 
            this.panel_face.ContextMenuStrip = this.contextMenuStrip1;
            this.panel_face.Controls.Add(this.treeView1);
            this.panel_face.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel_face.Location = new System.Drawing.Point(0, 0);
            this.panel_face.Name = "panel_face";
            this.panel_face.Size = new System.Drawing.Size(391, 238);
            this.panel_face.TabIndex = 0;
            this.panel_face.Visible = false;
            this.panel_face.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter);
            // 
            // contextMenuStrip1
            // 
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.Tool_Ima,
            this.Tool_File});
            this.contextMenuStrip1.Name = "contextMenuStrip2";
            this.contextMenuStrip1.Size = new System.Drawing.Size(153, 70);
            // 
            // Tool_Ima
            // 
            this.Tool_Ima.Name = "Tool_Ima";
            this.Tool_Ima.Size = new System.Drawing.Size(152, 22);
            this.Tool_Ima.Tag = "1";
            this.Tool_Ima.Text = "拖放圖片";
            this.Tool_Ima.Click += new System.EventHandler(this.Tool_Ima_Click);
            // 
            // Tool_File
            // 
            this.Tool_File.Name = "Tool_File";
            this.Tool_File.Size = new System.Drawing.Size(152, 22);
            this.Tool_File.Tag = "2";
            this.Tool_File.Text = "拖放文件夾";
            this.Tool_File.Click += new System.EventHandler(this.Tool_Ima_Click);
            // 
            // treeView1
            // 
            this.treeView1.AllowDrop = true;
            this.treeView1.ContextMenuStrip = this.contextMenuStrip1;
            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(391, 238);
            this.treeView1.TabIndex = 0;
            this.treeView1.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseDoubleClick);
            this.treeView1.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter);
            // 
            // Form1
            // 
            this.AccessibleRole = System.Windows.Forms.AccessibleRole.None;
            this.AllowDrop = true;
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(391, 238);
            this.ContextMenuStrip = this.contextMenuStrip1;
            this.Controls.Add(this.panel_face);
            this.Name = "Form1";
            this.Text = "向窗體中拖放圖片並顯示";
            this.DragEnter += new System.Windows.Forms.DragEventHandler(this.Form1_DragEnter);
            this.panel_face.ResumeLayout(false);
            this.contextMenuStrip1.ResumeLayout(false);
            this.ResumeLayout(false);

        }

 

而後綁定兩個鼠標右鍵的點擊事件爲同一個事件。線程

 private void Tool_Ima_Click(object sender, EventArgs e)
        {
            SetDragHandle(sender, treeView1);
        }

 

而後在點擊事件中調用方法SetDragHandle進行Panel或者TreeView的顯示控制。code

Var_Style標識變量爲true表示是拖拽照片模式,不然爲拖拽文件夾模式。component

public void SetDragHandle(object sender, TreeView TV)
        {
            //獲取Tag標籤內容
            switch (Convert.ToInt16(((ToolStripMenuItem)sender).Tag.ToString()))
            {
                case 1:
                    {
                        //讓面板隱藏
                        panel_face.Visible = false;
                        //設置標識變量爲true,true表示是拖拽圖片模式
                        Var_Style = true;
                        break;
                    }
                case 2:
                    {
                        this.Width = 399;
                        this.Height = 272;
                        panel_face.Visible = true;
                        Var_Style = false;
                        break;
                    }
            }
        }

 

兩個鼠標右鍵的點擊事件就是如上進行標識變量的設置,進而知道下一步要進行的操做是啥。orm

而後綁定panel和treeView以及窗體的拖拽事件爲同一個事件對象

 private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            //在窗體背景中顯示拖拽的照片
            SetDragImageToFrm(this, e);
            //清除treeView的全部節點
            treeView1.Nodes.Clear();
            //向TreeView控件添加被拖拽的文件夾的目錄
            SetDragImageToFrm(treeView1, e);
        }

 

在拖拽事件中執行三個操做方法,分別爲在窗體背景中顯示拖拽的照片的SetDragImageToFrm,清除treeView的blog

全部節點以及向treeView控件中添加被拖拽的文件夾的目錄。

在方法SetDragImageToFrm中,首先會根據是不是拖拽照片的標識變量進行判斷

若是是拖拽照片模式則獲取拖拽照片的路徑並將當前窗體的背景照片設置爲拖拽的照片。

public void SetDragImageToFrm(Form Frm, DragEventArgs e)
        {
            //若是顯示照片的標識變量爲true
            if (Var_Style == true)
            {
                //設置拖放操做中目標放置類型爲複製
                e.Effect = DragDropEffects.Copy;
                String[] str_Drop = (String[])e.Data.GetData(DataFormats.FileDrop, true);
                string tempstr;
                Bitmap bkImage;
                //獲取拖拽圖片的路徑
                tempstr = str_Drop[0];
                try
                {
                    bkImage = new Bitmap(tempstr);
                    Frm.Size = new System.Drawing.Size(bkImage.Width + 6, bkImage.Height + 33);
                    //設置當前窗體的背景圖片爲拖拽的照片
                    Frm.BackgroundImage = bkImage;
                }
                catch { }
            }
        }

 

而後在重載方法SetDragImageToFrm中注意此時傳遞的參數不一樣,此時傳遞的參數是TreeView控件。

public void SetDragImageToFrm(TreeView TV, DragEventArgs e)
        {
            //標識變量表示拖拽模式爲文件夾
            if (Var_Style == false)
            {
                e.Effect = DragDropEffects.Copy;
                String[] str_Drop = (String[])e.Data.GetData(DataFormats.FileDrop, true);
                tempstr = str_Drop[0];//獲取拖放文件夾的目錄
                thdAddFile = new Thread(new ThreadStart(SetAddFile));   //建立一個線程
                thdAddFile.Start(); //執行當前線程
            }
        }

 

在上面的方法中獲取拖拽文件夾的目錄,而後建立一個線程並執行。

線程執行SetAddFile方法,在此方法中設置託管線程

public void SetAddFile()
        {
            this.Invoke(new AddFile(RunAddFile));//對指定的線程進行託管
        }

 

在方法RunAddFile設置線程

 

public void RunAddFile()
        { 
            TreeNode TNode = new TreeNode();//實例化一個線程
            Files_Copy(treeView1, tempstr, TNode, 0);
            Thread.Sleep(0);//持起主線程
            thdAddFile.Abort();//執行線程      
        }

 

在上面方法中執行FIles_Copy方法顯示文件夾下全部文件夾和文件的名稱。

#region  顯示文件夾下全部子文件夾及文件的名稱
        /// <summary>
        /// 顯示文件夾下全部子文件夾及文件的名稱
        /// </summary>
        /// <param Sdir="string">文件夾的目錄</param>
        /// <param TNode="TreeNode">節點</param>
        /// <param n="int">標識,判斷當前是文件夾,仍是文件</param>
        private void Files_Copy(TreeView TV, string Sdir, TreeNode TNode, int n)
        {
            DirectoryInfo dir = new DirectoryInfo(Sdir);
            try
            {
                if (!dir.Exists)//判斷所指的文件或文件夾是否存在
                {
                    return;
                }
                DirectoryInfo dirD = dir as DirectoryInfo;//若是給定參數不是文件夾則退出
                if (dirD == null)//判斷文件夾是否爲空
                {
                    return;
                }
                else
                {
                    if (n == 0)
                    {
                        TNode = TV.Nodes.Add(dirD.Name);//添加文件夾的名稱
                        TNode.Tag = 1;
                    }
                    else
                    {
                        TNode = TNode.Nodes.Add(dirD.Name);//添加文件夾裏面各文件夾的名稱
                        TNode.Tag = 1;
                    }
                }
                FileSystemInfo[] files = dirD.GetFileSystemInfos();//獲取文件夾中全部文件和文件夾
                //對單個FileSystemInfo進行判斷,若是是文件夾則進行遞歸操做
                foreach (FileSystemInfo FSys in files)
                {
                    FileInfo file = FSys as FileInfo;
                    if (file != null)//若是是文件的話,進行文件的複製操做
                    {
                        FileInfo SFInfo = new FileInfo(file.DirectoryName + "\\" + file.Name);//獲取文件所在的原始路徑
                        TNode.Nodes.Add(file.Name);//添加文件
                        TNode.Tag = 1;
                    }
                    else
                    {
                        string pp = FSys.Name;//獲取當前搜索到的文件夾名稱
                        Files_Copy(TV, Sdir + "\\" + FSys.ToString(), TNode, 1);//若是是文件夾,則進行遞歸調用
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }
        #endregion

 

完整示例代碼

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;
using System.IO;//添加的命名空間,對文件進行操做
using System.Threading;//線程序的命名空間

namespace 向窗體中拖放圖片並顯示
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public static bool Var_Style = true;
        public static string tempstr="";
        private System.Threading.Thread thdAddFile; //建立一個線程
        private System.Threading.Thread thdOddDocument; //建立一個線程
        public static TreeNode TN_Docu = new TreeNode();//單個文件的節點
        private static TreeView Tem_TView;

        /// <summary>
        /// 在窗體背景中顯示被拖放的圖片
        /// </summary>
        /// <param Frm="Form">窗體</param>
        /// <param e="DragEventArgs">DragDrop、DragEnter 或 DragOver 事件提供數據</param>
        public void SetDragImageToFrm(Form Frm, DragEventArgs e)
        {
            //若是顯示照片的標識變量爲true
            if (Var_Style == true)
            {
                //設置拖放操做中目標放置類型爲複製
                e.Effect = DragDropEffects.Copy;
                String[] str_Drop = (String[])e.Data.GetData(DataFormats.FileDrop, true);
                string tempstr;
                Bitmap bkImage;
                //獲取拖拽圖片的路徑
                tempstr = str_Drop[0];
                try
                {
                    bkImage = new Bitmap(tempstr);
                    Frm.Size = new System.Drawing.Size(bkImage.Width + 6, bkImage.Height + 33);
                    //設置當前窗體的背景圖片爲拖拽的照片
                    Frm.BackgroundImage = bkImage;
                }
                catch { }
            }
        }

        /// <summary>
        /// 向TreeView控件添加被拖放的文件夾目錄
        /// </summary>
        /// <param TV="TreeView">TreeView控件</param>
        /// <param e="DragEventArgs">DragDrop、DragEnter 或 DragOver 事件提供數據</param>
        public void SetDragImageToFrm(TreeView TV, DragEventArgs e)
        {
            //標識變量表示拖拽模式爲文件夾
            if (Var_Style == false)
            {
                e.Effect = DragDropEffects.Copy;
                String[] str_Drop = (String[])e.Data.GetData(DataFormats.FileDrop, true);
                tempstr = str_Drop[0];//獲取拖放文件夾的目錄
                thdAddFile = new Thread(new ThreadStart(SetAddFile));   //建立一個線程
                thdAddFile.Start(); //執行當前線程
            }
        }


        public delegate void AddFile();//定義託管線程
        /// <summary>
        /// 設置託管線程
        /// </summary>
        public void SetAddFile()
        {
            this.Invoke(new AddFile(RunAddFile));//對指定的線程進行託管
        }

        /// <summary>
        /// 設置線程
        /// </summary>
        public void RunAddFile()
        { 
            TreeNode TNode = new TreeNode();//實例化一個線程
            Files_Copy(treeView1, tempstr, TNode, 0);
            Thread.Sleep(0);//持起主線程
            thdAddFile.Abort();//執行線程      
        }

        #region  返回上一級目錄
        /// <summary>
        /// 返回上一級目錄
        /// </summary>
        /// <param dir="string">目錄</param>
        /// <returns>返回String對象</returns>
        public string UpAndDown_Dir(string dir)
        {
            string Change_dir = "";
            Change_dir = Directory.GetParent(dir).FullName;
            return Change_dir;
        }
        #endregion

        #region  顯示文件夾下全部子文件夾及文件的名稱
        /// <summary>
        /// 顯示文件夾下全部子文件夾及文件的名稱
        /// </summary>
        /// <param Sdir="string">文件夾的目錄</param>
        /// <param TNode="TreeNode">節點</param>
        /// <param n="int">標識,判斷當前是文件夾,仍是文件</param>
        private void Files_Copy(TreeView TV, string Sdir, TreeNode TNode, int n)
        {
            DirectoryInfo dir = new DirectoryInfo(Sdir);
            try
            {
                if (!dir.Exists)//判斷所指的文件或文件夾是否存在
                {
                    return;
                }
                DirectoryInfo dirD = dir as DirectoryInfo;//若是給定參數不是文件夾則退出
                if (dirD == null)//判斷文件夾是否爲空
                {
                    return;
                }
                else
                {
                    if (n == 0)
                    {
                        TNode = TV.Nodes.Add(dirD.Name);//添加文件夾的名稱
                        TNode.Tag = 1;
                    }
                    else
                    {
                        TNode = TNode.Nodes.Add(dirD.Name);//添加文件夾裏面各文件夾的名稱
                        TNode.Tag = 1;
                    }
                }
                FileSystemInfo[] files = dirD.GetFileSystemInfos();//獲取文件夾中全部文件和文件夾
                //對單個FileSystemInfo進行判斷,若是是文件夾則進行遞歸操做
                foreach (FileSystemInfo FSys in files)
                {
                    FileInfo file = FSys as FileInfo;
                    if (file != null)//若是是文件的話,進行文件的複製操做
                    {
                        FileInfo SFInfo = new FileInfo(file.DirectoryName + "\\" + file.Name);//獲取文件所在的原始路徑
                        TNode.Nodes.Add(file.Name);//添加文件
                        TNode.Tag = 1;
                    }
                    else
                    {
                        string pp = FSys.Name;//獲取當前搜索到的文件夾名稱
                        Files_Copy(TV, Sdir + "\\" + FSys.ToString(), TNode, 1);//若是是文件夾,則進行遞歸調用
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }
        #endregion

        public void SetDragHandle(object sender, TreeView TV)
        {
            //獲取Tag標籤內容
            switch (Convert.ToInt16(((ToolStripMenuItem)sender).Tag.ToString()))
            {
                case 1:
                    {
                        //讓面板隱藏
                        panel_face.Visible = false;
                        //設置標識變量爲true,true表示是拖拽圖片模式
                        Var_Style = true;
                        break;
                    }
                case 2:
                    {
                        this.Width = 399;
                        this.Height = 272;
                        panel_face.Visible = true;
                        Var_Style = false;
                        break;
                    }
            }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            //在窗體背景中顯示拖拽的照片
            SetDragImageToFrm(this, e);
            //清除treeView的全部節點
            treeView1.Nodes.Clear();
            //向TreeView控件添加被拖拽的文件夾的目錄
            SetDragImageToFrm(treeView1, e);
        }

        private void Tool_Ima_Click(object sender, EventArgs e)
        {
            SetDragHandle(sender, treeView1);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Tem_TView = new TreeView();
            Tem_TView = treeView1;

        }
        string Tem_Dir = "";
        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Tag == null)
                Tem_Dir = "";
            else
                Tem_Dir = e.Node.Tag.ToString();
            if (Tem_Dir == "")
            {
                Tem_Dir = UpAndDown_Dir(tempstr) + "\\" + e.Node.FullPath;
                System.Diagnostics.Process.Start(@Tem_Dir);//打開當前文件
            }

        }
    }
}

代碼下載

https://download.csdn.net/download/BADAO_LIUMANG_QIZHI/12027852

相關文章
相關標籤/搜索