C#中的拖放功能使我們在做一些時(shí)變得非常方便,下面就以一個(gè)實(shí)例講解了具體的拖放操作的實(shí)現(xiàn)方法。
下面的代碼沒有給出注釋,加入了一個(gè)ListBox,當(dāng)文件拖放上來后,將內(nèi)容顯示在里面。
private void lstFilePath_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Link;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void lstFilePath_DragDrop(object sender, DragEventArgs e)
{
foreach (string strPath in (string[])e.Data.GetData(DataFormats.FileDrop))
{
lstFilePath.Items.Add(strPath);
}
}
將整個(gè)窗體代碼都復(fù)制下來,是一個(gè)復(fù)制的小程序,將拖放到LISTBOX里的文件復(fù)制到文本框里指定的位置,里面用到了一個(gè)外部控件,可以使用普通的button替換之。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace PersonalDisk
{
public partial class frmDrag : Form
{
///
/// 獲得/設(shè)置一個(gè)值,判斷是否已經(jīng)存在了一個(gè)類的實(shí)例
///
public static bool IsExist=false;
public frmDrag()
{
InitializeComponent();
frmDrag.IsExist = true;
}
private void frmDrag_MouseDown(object sender, MouseEventArgs e)
{
//如果鼠標(biāo)指針在標(biāo)題欄范圍內(nèi)并且按下了鼠標(biāo)左鍵,則觸發(fā)移動(dòng)標(biāo)題欄方法
if (e.Button == MouseButtons.Left e.Y
/// 復(fù)制一個(gè)目錄下的所有文件或目錄到一個(gè)新的目錄下
///
/// 源目錄路徑
/// 目標(biāo)目錄路徑
private void CopyDirectory(string sourcePath, string destPath)
{
try
{
//如果目標(biāo)路徑?jīng)]有以/結(jié)尾則加之
if (destPath[destPath.Length - 1] != Path.DirectorySeparatorChar)
{
destPath += Path.DirectorySeparatorChar;
}
if (!Directory.Exists(destPath))
{
Directory.CreateDirectory(destPath);
}
string[] fileList = Directory.GetFileSystemEntries(sourcePath);
foreach (string file in fileList)
{
//如果是一個(gè)目錄則
if (Directory.Exists(file))
{
CopyDirectory(file, destPath + Path.GetFileName(file));
}
else
{
File.Copy(file, destPath + Path.GetFileName(file),true);
}
}
}
catch(IOException ioe)
{
MessageBox.Show(ioe.Message, "復(fù)制文件時(shí)出錯(cuò)", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
新聞熱點(diǎn)
疑難解答
圖片精選