Connecting Tech Pros Worldwide
Ph: 0000000000
 
 
sign in | join about | help | sitemap
[ http://bytes.com/adLoader.php?parent=general

Dragging and Dropping Files Into your C#.NET Program

Written by insertAlias, August 20th, 2008
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
this.AllowDrop = true;

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
this.DragEnter += new DragEventHandler(Form1_DragEnter); this.DragDrop += new DragEventHandler(Form1_DragDrop);

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
if (e.Data.GetDataPresent(DataFormats.FileDrop, false))     e.Effect = DragDropEffects.All;

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
string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[]; foreach (string s in fileList) {     //replace this with your own code     textBox1.Text += String.Format("{0}{1}", s, Environment.NewLine); }

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
text.exe c:\dev\temp.txt

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
static void Main(string[] args) {   //your code }

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
static void Main(); //should become: static void Main(string[] args)

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
public Form1() {     InitializeComponent(); }

Change it to this:
C#
Expand|Select|Wrap|Line Numbers
public Form1(string[] args) {     InitializeComponent(); }

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
public Form1(string[] args) {     Application.Run(new Form1());     //should become     Application.Run(new Form1(args)); }

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
using System; using System.Windows.Forms;   namespace DragDrop {     static class Program     {         /// <summary>         /// The main entry point for the application.         /// </summary>         [STAThread]         static void Main(string[] args)         {             Application.EnableVisualStyles();             Application.SetCompatibleTextRenderingDefault(fals  e);             Application.Run(new Form1(args));         }     } }

Form1.cs
C#
Expand|Select|Wrap|Line Numbers
using System; using System.Windows.Forms;   namespace DragDrop {     public partial class Form1 : Form     {         public Form1(string[] args)         {             InitializeComponent();         }     } }

12 Comments Posted ( Post your comment )
insertAlias / August 20th, 2008 03:28 AM
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.
Reply
KUB365 / August 21st, 2008 11:26 PM
article looks good, not that great at vb.net myself to be of any help.
Reply
insertAlias / August 22nd, 2008 09:40 PM
Made a few changes.

Looks like nobody's interested in helping or commenting =(
Reply
KevinADC / August 22nd, 2008 11:01 PM
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.
Reply
insertAlias / August 23rd, 2008 02:12 AM
Thanks Kevin.
Reply
kenobewan / August 25th, 2008 01:38 PM
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).
Reply
insertAlias / August 25th, 2008 04:55 PM
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.
Reply
joedeene / September 29th, 2008 01:30 AM
***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().
Reply
Plater / September 29th, 2008 06:01 PM
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)
Reply
andyuk0000000000 / October 8th, 2008 08:09 PM
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.
Reply
joedeene / October 8th, 2008 08:21 PM
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
Reply
insertAlias / October 8th, 2008 08:39 PM
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
Post your comment about this Howto

Stats:
Comments: 12


You are viewing a mobilized version of this site...
View original page here

How do you rate mobile version of this page?

Mobilized by Mowser Mowser