C#中的拖放功能使我們在做一些時變得非常方便,下面就以一個實例講解了具體的拖放操作的實現方法。
下面的代碼沒有給出注釋,加入了一個ListBox,當文件拖放上來后,將內容顯示在里面。
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);
}
}
將整個窗體代碼都復制下來,是一個復制的小程序,將拖放到LISTBOX里的文件復制到文本框里指定的位置,里面用到了一個外部控件,可以使用普通的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
{
///
/// 獲得/設置一個值,判斷是否已經存在了一個類的實例
///
public static bool IsExist=false;
public frmDrag()
{
InitializeComponent();
frmDrag.IsExist = true;
}
private void frmDrag_MouseDown(object sender, MouseEventArgs e)
{
//如果鼠標指針在標題欄范圍內并且按下了鼠標左鍵,則觸發移動標題欄方法
if (e.Button == MouseButtons.Left e.Y
/// 復制一個目錄下的所有文件或目錄到一個新的目錄下
///
/// 源目錄路徑
/// 目標目錄路徑
private void CopyDirectory(string sourcePath, string destPath)
{
try
{
//如果目標路徑沒有以/結尾則加之
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)
{
//如果是一個目錄則
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, "復制文件時出錯", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
新聞熱點
疑難解答
圖片精選