Connecting Tech Pros Worldwide Forums | Help | Site Map

Dragging and Dropping Files Into your C#.NET Program

insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#1   Aug 20 '08
You might have noticed that for some programs, you can drag files directly into them. This is a useful feature: it lets you save the time and effort required to open a file dialog box, and allows you to easily work with several files. For example, I just recently wrote a file renaming program, that can add/remove text from files that you drag onto it. Also, some programs let you drag a file onto its executable or shortcut. I'll show you how to enable both in your .NET programs.

Drag/Drop onto Windows Forms

The Form class, along with several others, supports drag/drop. We'll assume that you are dragging/dropping directly to the form.

Start by setting the AllowDrop property to true. You can do this in the properties window or in code:
Expand|Select|Wrap|Line Numbers
  1. this.AllowDrop = true;
  2.  
Now that the form will accept dragging/dropping, we need some events to handle this. Let's add event handlers for DragEnter and DragDrop. You can do this in the properties window. Click the lightning bolt icon, and find the events. Double-click the blank space beside them.


Otherwise, you can do this in code. You will want to do this in the constructor after the InitializeComponent() call.
C#
Expand|Select|Wrap|Line Numbers
  1. this.DragEnter += new DragEventHandler(Form1_DragEnter);
  2. this.DragDrop += new DragEventHandler(Form1_DragDrop);
  3.  
Now, let's fill in the events. We want our cursor to change to the drop cursor when we drag over the form. So in the Form1_DragEnter event, put this code:
C#
Expand|Select|Wrap|Line Numbers
  1. if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
  2.     e.Effect = DragDropEffects.All;
  3.  
This shows DragDrop effects if there is data available, and it is in the format of a file drop.

Now, we need to do something with the data when the file(s) are dropped. Here's the code to put into your Form1_DragDrop event.
C#
Expand|Select|Wrap|Line Numbers
  1. string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[];
  2. foreach (string s in fileList)
  3. {
  4.     //replace this with your own code
  5.     textBox1.Text += String.Format("{0}{1}", s, Environment.NewLine);
  6. }
  7.  
The data is a string array, but is returned as an object, so it must be typecasted. So fileList is now holding the paths to the files that have been dropped. I've added the filenames to a TextBox, but you can do whatever you want with them. System.IO.FileInfo is a very useful class for handling files. Now you can handle files dropped into your program.

Drag/Drop onto Shortcut/Executable
Note: This doesn't work with shortcuts created by a setup package

You might want to be able to drag a file onto your desktop icon, and have the program start up and do something with that file. This is also possible.

When you drop a file onto an executable or it's shortcut, the path to that file is treated as an command line argument. So, if I dragged the file C:\Dev\temp.txt onto text.exe, it would be the same as if I ran this from the command line:
DOS Command Line
Expand|Select|Wrap|Line Numbers
  1. text.exe c:\dev\temp.txt
  2.  
Now you need to know how to get to these arguments. If you have made Command line programs, you may have noticed the parameter in your Main function:
C#
Expand|Select|Wrap|Line Numbers
  1. static void Main(string[] args)
  2. {
  3.   //your code
  4. }
  5.  
string[] args contains a list of the arguments. So, if we continue the previous example, args[0] would contain: @"c:\dev\temp.txt".

You can drop several files at once on the executable as well. These file paths will show up individually in the args array. So, you can loop through the args array to get all files dropped on your program.

But Windows Forms applications don't have this parameter by default. So how would you get that information to your Form? Well, you have to modify the Main method. Find your Main method in Program.cs:
C#
Expand|Select|Wrap|Line Numbers
  1. static void Main();
  2. //should become:
  3. static void Main(string[] args)
  4.  
Now you have access to the arguments, but you need to get them to your form. There is more than one way to do this, but I suggest modifying your constructor. Lets assume we are working with Form1. The old constructor looks like this:
C#
Expand|Select|Wrap|Line Numbers
  1. public Form1()
  2. {
  3.     InitializeComponent();
  4. }
  5.  
Change it to this:
C#
Expand|Select|Wrap|Line Numbers
  1. public Form1(string[] args)
  2. {
  3.     InitializeComponent();
  4. }
  5.  
Now your form will take a string array as a constructor parameter. Go back to Program.cs, and change the way you call Form1.
C#
Expand|Select|Wrap|Line Numbers
  1. public Form1(string[] args)
  2. {
  3.     Application.Run(new Form1());
  4.     //should become
  5.     Application.Run(new Form1(args));
  6. }
  7.  
Now you have access to your command line arguments in your form. You can store them, or do whatever you want with them.

Since the back and forth between the two pages can be a bit confusing, here's the full code for the program and the form.
Program.cs
C#
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Windows.Forms;
  3.  
  4. namespace DragDrop
  5. {
  6.     static class Program
  7.     {
  8.         /// <summary>
  9.         /// The main entry point for the application.
  10.         /// </summary>
  11.         [STAThread]
  12.         static void Main(string[] args)
  13.         {
  14.             Application.EnableVisualStyles();
  15.             Application.SetCompatibleTextRenderingDefault(false);
  16.             Application.Run(new Form1(args));
  17.         }
  18.     }
  19. }
  20.  
Form1.cs
C#
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Windows.Forms;
  3.  
  4. namespace DragDrop
  5. {
  6.     public partial class Form1 : Form
  7.     {
  8.         public Form1(string[] args)
  9.         {
  10.             InitializeComponent();
  11.         }
  12.     }
  13. }



insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#2   Aug 20 '08

re: Dragging and Dropping Files Into your C#.NET Program


This is my first draft of this article. If anyone wants to help by supplying me with some VB.NET sample code, it would be much appreciated.

I just don't usually work with VB.NET, and it's a bit different.
KUB365's Avatar
Administrator
 
Join Date: Jul 2005
Location: Portland, OR
Posts: 969
#3   Aug 21 '08

re: Dragging and Dropping Files Into your C#.NET Program


article looks good, not that great at vb.net myself to be of any help.
insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#4   Aug 22 '08

re: Dragging and Dropping Files Into your C#.NET Program


Made a few changes.

Looks like nobody's interested in helping or commenting =(
KevinADC's Avatar
Expert
 
Join Date: Jan 2007
Location: Southern California USA
Posts: 4,091
#5   Aug 22 '08

re: Dragging and Dropping Files Into your C#.NET Program


I don't know .NET or VB either, but the article is well written. Easy to read and follow, grammar is very good too. Should be also easy for non-native English speakers to read and understand. Good job.
insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#6   Aug 23 '08

re: Dragging and Dropping Files Into your C#.NET Program


Thanks Kevin.
kenobewan's Avatar
Moderator
 
Join Date: Dec 2006
Posts: 4,745
#7   Aug 25 '08

re: Dragging and Dropping Files Into your C#.NET Program


I'm not a windows programmer, I could try convert this C# code into VB but the methods etc would be wrong; even if the formatting was right. So the next best thing is to give you a link, using similar events:
Drag and Drop Images Into a PictureBox
Hope this helps :o).
insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#8   Aug 25 '08

re: Dragging and Dropping Files Into your C#.NET Program


Thanks, Ken. I think that I can handle the first part. The second section is what is so foreign to me. In C# Win Forms, you have a Program.cs, the entry point for your program, the one with your Main() method. In VB.NET, you have something like a config page, in which you specify which is your startup form. I don't see where you can get your command line arguments from VB.NET Win Forms. If anyone knows where I can get to the Main() method in VB.NET, let me know.
joedeene's Avatar
Site Addict
 
Join Date: Jul 2008
Location: US of A
Posts: 587
#9   Sep 29 '08

re: Dragging and Dropping Files Into your C#.NET Program


***BELOW IS A QUOTE FROM A MEMBER FROM A DIFFERENT FORUM.
---------------------------------------------------------------------
Quote:

Originally Posted by Mike R

Yep!

You won't find this in VB.NET windows application because VB.NET uses a 'Startup Form' setting within the Project Propertes page, on the Application tab. (And therefore the actual entrypoint is hidden from us.) But a VB.NET console application does use a Sub Main().

Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,161
#10   Sep 29 '08

re: Dragging and Dropping Files Into your C#.NET Program


I just noticed this article now. I find the articles very difficult to search/navigate. So I miss these generally.
Looks good, although I recomend more language about the datatypes and allowing or dissalowing certain types. Like in your example you would only want to allow "files" to be dropped, and not other dragable items (such as text or images)
Newbie
 
Join Date: Oct 2008
Posts: 6
#11   Oct 8 '08

re: Dragging and Dropping Files Into your C#.NET Program


Hi, If you want VB examples, why not just open your binary in .NET Reflector, you can view the source in VB or C#.

You can get arguments using the Enviroment.CommandLine property or the Environment.GetCommandLineArgs() method.
joedeene's Avatar
Site Addict
 
Join Date: Jul 2008
Location: US of A
Posts: 587
#12   Oct 8 '08

re: Dragging and Dropping Files Into your C#.NET Program


Quote:

Originally Posted by andyuk0000000000

Hi, If you want VB examples, why not just open your binary in .NET Reflector, you can view the source in VB or C#.

It's not about having trouble converting code by code, experts here, in that area, have no problem in that area. The problem is that VB.NET Windows Application source files do not have a Main() function as you would in a normal C#.NET Windows Applications, because the compiler for VB.NET slacks a bit more for the more-beginner programmer.

joedeene
insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#13   Oct 8 '08

re: Dragging and Dropping Files Into your C#.NET Program


Well, thanks for the suggestions, but I have found a workaround, that will make this code even easier in C# and VB.NET:
Environment.GetCommandLineArgs Method
This will return an array strings of the command line args, the first being the name of the executable, the following (if any) the arguments.
No modifying the main method or constructors needed =D

I'll try to update the article later if I get time, but for now I want to get it out there in the Comments section.

Thanks to balabaster for helping me find this.
Reply