Return to Snippet

Revision: 39198
at January 14, 2011 12:36 by kyrathaba


Initial Code
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
}

Initial URL
http://kyrathaba.dcmembers.com/errata/openFileDroppedOntoForm.htm

Initial Description
Example written 01/13/2011

The following code shows how to implement functionality in your Windows Forms application, such that you'll be able to open a file that is dragged and dropped onto your program's form. This behavior is often desirable for programs that manipulate files in some way (renamers, encrypters, etc.) It's also nice for the uer to be able to have more than one way to open a file. This example implements opening via drag-dropping, and via a customary File->Open menu.

Initial Title
Drag file onto form to open file

Initial Tags
form, file

Initial Language
C#