這個例子是将系統檔案或目錄拖動到窗體中,窗體以MessageBox的形式彈出使用者拖入的檔案或目錄名稱。首先需要将要支援拖動的Form的AllowDrop=true;然後通過DragEnter和DragDrop事件即可,具體代碼如下:
private void Form1_DragDrop(object sender, DragEventArgs e)
{
System.Array datas = (System.Array)e.Data.GetData(DataFormats.FileDrop);
string filePathOrDirectory = (datas).GetValue(0).ToString();
if (Directory.Exists(filePathOrDirectory))
{
MessageBox.Show("目錄:" + filePathOrDirectory);
}
else
{
MessageBox.Show("檔案:" + filePathOrDirectory);
}
}
private void Form1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop) == true)
e.Effect = DragDropEffects.Link;
else
e.Effect = DragDropEffects.None;
}