using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace BryanWinForms1 {
public partial class Form1 : Form {
private delegate void DelegateOpenFile(String s); //define delegate type
DelegateOpenFile _openFileDelegate; //declares a delegate instance
public Form1() {
InitializeComponent();
this.AllowDrop = true; //must set this to true, for dragDrop to work
//delegate needed so Form1_DragDrop() can asynchronously
//invoke our program's OpenFile() method
_openFileDelegate
= new DelegateOpenFile
(this.OpenFile); //instantiates delegate }
private void openToolStripMenuItem_Click(object sender, EventArgs e) {
OpenFileDialog openDlg
= new OpenFileDialog
(); openDlg.Filter = "Any File (*.*)|*.*";
openDlg.FileName = "";
openDlg.CheckFileExists = true;
openDlg.CheckPathExists = true;
if (openDlg.ShowDialog() != DialogResult.OK)
return;
OpenFile(openDlg.FileName);
}
private void OpenFile(string sFile) {
//insert appropriate file-opening code here...
MessageBox.Show("\"" + sFile + "\" will be opened.");
}
private void Form1_DragEnter(object sender, DragEventArgs e) {
//we're only interested if a FILE was dropped on the form
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void Form1_DragDrop(object sender, DragEventArgs e) {
//good idea to use try-catch block, in case something goes wrong
try {
Array a = (Array)e.Data.GetData(DataFormats.FileDrop);
if (a != null) {
// Extract string from first array element
// (ignore all files except first if number of files are dropped).
string s = a.GetValue(0).ToString();
// Call OpenFile asynchronously.
// Explorer instance from which file is dropped is not responding
// the entire time that the DragDrop handler is active, so we need to return
// immidiately (especially if OpenFile shows MessageBox).
this.BeginInvoke(_openFileDelegate,
new Object[] { s
}); this.Activate(); // in the case Explorer overlaps this form
}
}
catch (Exception ex) {
Trace.WriteLine("Error in DragDrop function: " + ex.Message);
// don't show MessageBox here - Explorer is waiting !
}
}
//next right-brace ends Form1 class
}
//next right-brace ends namespace
}