DonationCoder.com forum
 
Read-only archive. This is a static copy of the DonationCoder.com forum. Reading and searching work as before; logging in, posting and private messages do not.
Archive of 2026-10-21 · About this archive · Main site

Author Topic: Open a File by dropping it onto Form (C# example)  (Read 4,654 times)

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • Participated in NANY Challenge Eight Times
    • Programming School - Deluxe Bonus Medal
    • Programming School - Stage 1 Medal
    • Coding Snacks
    • Military Service Badge - US Army
    • Writer
Open a File by dropping it onto Form (C# example)
« on: January 14, 2011, 12:52 AM »
Since I researched and implemented this for a recent short project, I thought I'd make it available in case it might benefit any other C# developers:

Sample Code for Opening a File Dropped onto Form.
Win 10 Pro running on a 3.2 GHz CPU and 12 Gb RAM
__________________________________________

Proofreading Service: http://williammillerservices.com/proofreading

f0dder

  • [Well, THAT escalated quickly!]
  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,153
    • Participated in NANY Challenge Once
Re: Open a File by dropping it onto Form (C# example)
« Reply #1 on: January 14, 2011, 12:55 AM »
In case you're going to semi-regularly post code snippets, you should check out SyntaxHighlighter - it's nice :)
- carpe noctem

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • Participated in NANY Challenge Eight Times
    • Programming School - Deluxe Bonus Medal
    • Programming School - Stage 1 Medal
    • Coding Snacks
    • Military Service Badge - US Army
    • Writer
Re: Open a File by dropping it onto Form (C# example)
« Reply #2 on: January 14, 2011, 01:17 AM »
Thanks for the link.  I also like Veign's Code Highlighter.

Of course, I can also just use the site's code tags:

Code: (csharp)
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
}
Win 10 Pro running on a 3.2 GHz CPU and 12 Gb RAM
__________________________________________

Proofreading Service: http://williammillerservices.com/proofreading

Original address: https://www.donationcoder.com/forum/index.php?topic=25216.0