需要知道的ListBox的兩個(gè)事件:當(dāng)您在控件的邊界內(nèi)拖動(dòng)對(duì)象時(shí),便會(huì)發(fā)生 DragEnter 事件;該事件用于確
定當(dāng)前拖動(dòng)的對(duì)象是不是您要放到控件上的對(duì)象。 在將一個(gè)或多個(gè)文件拖到控件上時(shí),需要處理此事件。 這使
得在將對(duì)象拖到控件上方時(shí),能夠根據(jù)所拖動(dòng)的對(duì)象顯示相應(yīng)的圖標(biāo)。 將拖動(dòng)的對(duì)象釋放到控件上時(shí),會(huì)發(fā)生
DragDrop 事件。
功能描述:向ListBox拖入一個(gè)文件,ListBox顯示該文件的路徑,然后單擊該路徑,點(diǎn)擊Open按鈕打開(kāi)該文件。
代碼實(shí)現(xiàn):
需要將ListBox的AllowDrop屬性改為true,并實(shí)現(xiàn)它的DragEnter、DragDrop這兩個(gè)事件。
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();
}
///
/// 獲取ListBox的值。
///
///
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;
}
///
/// ListBox內(nèi)的值是否被選中。
///
///
public bool IsListBoxSelected()
{
bool selected;
if (lbFilePath.SelectedIndex == -1)//SelectedIndex==-1時(shí),表示未選中任何項(xiàng)。
{
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);
}
}
}
}
總結(jié):
Data 對(duì)象的 GetData 方法返回一個(gè)字符串?dāng)?shù)組,該數(shù)組包含拖到該列表框控件中的文件的完整路徑名。 可以使用此文件路徑信息來(lái)執(zhí)行需要對(duì)文件執(zhí)行的任何操作。