简体   繁体   中英

C#: Drag & Drop File on .exe (icon) and get filepath

I'm new to C# and I'm not getting around this trouble. Here is what I wanted to achieve. Whenever I drag and drop a file on the .exe file (on the icon itself), the application should capture the filepath of dragged file.

Thanks.

If I understand correctly, you want to drop a file onto an icon of an exe, not an application itself. If that is so, it can be achieved easily using the parameters passed into the application. If you check your original boilerplate code when you make a console application it has the application entry point:

static void Main(string[] args)

If you drag drop a file onto the icon of the application, the args[0] will hold the name of the file being dropped. If the goal is to drop the file onto an EXE file, there are numerous tutorials on SO about that.

If you make this following code, then when you drag your file onto the exe icon, the args[0] will hold the path of it as an argument: (I added the if statement that if you start the program without dragging anything it shouldn't crash)

class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                Console.WriteLine(args[0]);
            }
            Console.ReadLine();
        }
    }

I was able to add drag and drop onto an executable/shortcut created using Windows Forms by adding in the default string[] args to the Main function in Program . And then, add the same parameter to Form1 's constructor function, and pass in the same args gathered from Main .

Program.cs

static class Program
{
    [STAThread]
    //add in the string[] args parameter
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        //pass in the args to the form constructor
        Application.Run(new Form1(args));
    }
}

Form1.cs

//add in the string[] args parameter to the form constructor
public Form1(string[] args)
{
    InitializeComponent();

    //if there was a file dropped..
    if (args.Length > 0)
    {
        var file = args[0];
        //do something with the file now...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM