(C #) How to open a file in my program using drag and "Open with ..."
Windows has a function where you can drag a file into 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 the file, to go to the text editor part of my program.
string filePath = //Find path of file just opened
form_editScript edit = new form_editScript(filePath);
edit.Show();
Hide();
source to share
To be able to handle "Open with ..." you need to get the path to the file from the method args
Main
:
static void Main(string[] args)
{
string filePath = args.FirstOrDefault();
....
Application.Run(new form_editScript(filePath))
For the Drag-Drop part, you need to set the property to a AllowDrop
value AllowDrop
and then subscribe to events DragEnter
and DragDrop
. The DragEnter
check whether there is Data
a file, and then let fall. In, DragDrop
you get a string array with the files to discard:
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];
....
source to share