Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(C#) How to open a file in my program via drag and "Open with ..."

Tags:

c#

forms

Windows has a feature where you can drag a file onto a program or shortcut and it will say "Open with (program name)" I want to be able to do this for my program and when I open with a file be able to go to the text editor portion of my program.

string filePath = //Find path of file just opened
form_editScript edit = new form_editScript(filePath);
edit.Show();
Hide();
like image 433
Tanner H. Avatar asked Jan 21 '26 03:01

Tanner H.


1 Answers

To be able to handle the "Open with..." you will need to get the file path from the args of Main method:

static void Main(string[] args)
{
    string filePath = args.FirstOrDefault();
    ....
    Application.Run(new form_editScript(filePath))

For the Drag-Drop part you will have to set the form's AllowDrop property to true then subscribe to DragEnter and DragDrop events. In the DragEnter check if the Data is a file then allow the drop. In the DragDrop you will get string array with the files being dropped:

private void Form1_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effect = DragDropEffects.Link;
    }
}

private void Form1_DragDrop(object sender, DragEventArgs e)
{
    string filePath = ((string[]) e.Data.GetData(DataFormats.FileDrop))[0];
    ....
like image 160
Ofir Winegarten Avatar answered Jan 23 '26 17:01

Ofir Winegarten