Drag a file onto the EXE, and open it

B2Ben

Well-known member
Joined
Aug 17, 2006
Messages
52
Programming Experience
Beginner
I've written a program that saves it's data to an XML file. I'd like to be able to drag an XML file (in windows) onto the Executable. Then I want the program to launch, and open the file I just dragged on to it.

I'm sure this is a pretty straightforward task, but all of my forum and google searches keep turning up results for dragging & dropping within an application. If anybody knows some basic code to help me do this, or can point me to a tutorial, it would be greatly appreciated.

Thanks all,

- Ben
 
Nevermind... I found what I needed in the object browser:

VB.NET:
Dim CommandLine As String = System.Environment.CommandLine()
 
For posterity, here's what I came up with... Hopefully it will help someone else down the road:

VB.NET:
        'See if a file was dropped onto the application:
        'Imports System.Text.RegularExpressions
        'Command line looks something like this:
        '   "C:\MyAppFolder\MyApp.exe" "MyFirstDroppedFilePath.xml" "MySecondDroppedFilePath.xml"
        Dim CmdLineRegEx As New Regex("""(?<Path>[^""]+)""", RegexOptions.Compiled) 'Matches everything between quotes
        Dim MC As MatchCollection = CmdLineRegEx.Matches(System.Environment.CommandLine())
        'The first match is the path of the EXE... ignore that one
        If MC.Count = 2 Then  'Only act if we have the App Path and one dropped file
            Dim M As Match = MC(1) 'Grab the second match (index of 1)
            Dim Path As String = (M.Groups("Path").Value) 'Extract the path from the Regular Expression
            If (System.IO.Path.GetExtension(Path).ToUpper) = ".XML" Then
                'We have an XML file!  ...open it
                Me.OpenFile(Path)  'Open file with my custom function
            End If
        End If
 
Environment.GetCommandLineArgs method give you a string array of each argument, first element is always the executable filename.
 
for drag and drop you dont use any command line or command line args stuff, simply enable drag and drop for the form then use the DragEnter event to varify that it's a file drop, then in the DragDrop event you open the file and do whatever else is needed:

VB.NET:
    Private Sub frmMain_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles MyBase.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) = True Then
            e.Effect = DragDropEffects.Copy
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub frmMain_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles MyBase.DragDrop
        Dim strFileNames() As String = CType(GetDroppedFilePath(sender, e), String())
        If strFileNames(0) <> "" Then
            Call OpenFile(strFileNames(0))
        End If
    End Sub

    Private Function GetDroppedFilePath(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) As Array
        Dim strNames() As String, intCounter As Integer = 0I
        Dim strMyFileNames(intCounter) As String
        Try
            'a file dropped from Explorer:
            If e.Data.GetDataPresent(DataFormats.FileDrop, False) = True Then
                strNames = CType(e.Data.GetData(DataFormats.FileDrop), String())
                For Each strName As String In strNames
                    ReDim Preserve strMyFileNames(intCounter)
                    If strName.EndsWith("xml") = True Then strMyFileNames(intCounter) = strName
                    intCounter += 1
                Next strName
            End If
            Return strMyFileNames
        Catch ex As Exception
            Return strMyFileNames
        End Try
    End Function
 
It is default Windows (Explorer) behaviour when you drag one or more files onto an executable each filenamepath is supplied as a commandline argument. It also works with desktop shortcuts to executables. Useful in some cases when you don't need the application to be running but still be ready at all times for dropping files to process.
 
so drag and drop filenames can be retrieved with the Environment.GetCommandLineArgs instead of that last function to get the names from the file drop?
 
I think there's some confusion here. JB, what you have suggested is quite legitimate if the user wants to drag a file from Windows Explorer and drop it on a form in their application. The idea here, I think, is that the user should drag a data file in Windows Explorer and drop it on an executable file, also in Windows Explorer. That action would run the application and pass the path of the dropped file as a command line argument.
 
Back
Top