Vb.net file association in running inctance

vb .net 4 winforms vs 2010

I'm trying to get my file association to fire and load a double clicked file in a running instance. I have the association set up, it opens the program and loads fine. Where I am running into a problem is double clicking a file and getting it opened in a running instance of the program. So far I have no code on the main form to handle this.I am currently woking with application events. I have searched all over google and haven't found any good leads. It seems to me this should be easier. Any help would be greatly appreciated.


Application Events
 Namespace My

    ' The following events are available for MyApplication:
    ' 
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Partial Friend Class MyApplication

        Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
            Dim CmdArgs() As String = Environment.GetCommandLineArgs()



            If CmdArgs.Length > 0 Then

                For ArgNum = 0 To UBound(CmdArgs)
         


                    'RibbonForm1.RichEditControl1.LoadDocument(Command)
                    'RibbonForm1.textpanel.Dock = DockStyle.Fill
                    ' RibbonForm1.textpanel.BringToFront()

                Next ArgNum

            End If
 

        End Sub
    End Class


End Namespace

Open in new window

SkwerlzAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
ToddBeaulieuConnect With a Mentor Commented:
I don't think that's easy, at all.

Here's an entire CodePlex project demonstrating it.

http://www.codeproject.com/KB/vb/sing_inistan.aspx

From the second instance, you need to locate and communicate with another instance, asking it to load the document you were going to load.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Use "e.CommandLine" in the StartupNextInstance() event to get the filename.  The code you currently have will retrieve the parameters that were passed to the FIRST instance only.

See:
http://msdn.microsoft.com/en-us/library/b9z4eyh8(VS.80).aspx

    "You must use the CommandLine property of the e parameter to access the arguments for subsequent attempts to start a single-instance application. The My.Application.CommandLineArgs Property provides the arguments used to start the first instance of a single-instance application."

Use the forms NAME to pass the new filename to the default instance of that form.  You'll need to create a public method to accept the filename and do something with it.

For instance, if your "Startup Object" was Form1, then you could do something like:
 
Public Class Form1

    Public Sub OpenFile(ByVal args As Collections.ObjectModel.ReadOnlyCollection(Of String))
        ' ... do something with "args" to load passed file...
    End Sub

End Class

Open in new window


The StartupNextInstance() Event might look like:
 
Namespace My

    ' The following events are available for MyApplication:
    ' 
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Partial Friend Class MyApplication

        Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
            Form1.OpenFile(e.CommandLine)
        End Sub

    End Class


End Namespace

Open in new window

0
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
@Todd...that approach was necessary for VB.Net 2003 (and below).

VB.Net 2005 (and above) has the "Application Framework" which can handle this quite elegantly now.

See "Overview of the Visual Basic Application Model":
http://msdn.microsoft.com/en-us/library/w3xx6ewx(VS.80).aspx
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
ToddBeaulieuConnect With a Mentor Commented:
Oh, that's interesting. Thanks!
0
 
SkwerlzAuthor Commented:
I tried idle minds link.
I used the following

    Dim inputArgument As String = "/input="
    Dim inputName As String = ""

    For Each s As String In e.CommandLine
        If s.ToLower.StartsWith(inputArgument) Then
            inputName = s.Remove(0, inputArgument.Length)
        End If
    Next

    If inputName = "" Then
        MsgBox("No input name")
    Else
        MsgBox("Input name: " & inputName)
    End If

Open in new window


I get the "No input name" message box. I'm assuming this means I'm not getting the file path sent through? any thoughts?
0
 
SkwerlzAuthor Commented:
Ok revisited and here is what I have.

App events
  Partial Friend Class MyApplication

        Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
            Dim CmdArgs() As String = Environment.GetCommandLineArgs()
            If CmdArgs.Length > 0 Then
                For ArgNum = 0 To UBound(CmdArgs)

                    RibbonForm1.OpenFile(e.CommandLine)

                  

                Next ArgNum

            End If


        End Sub
    End Class

Open in new window


main form
    Public Sub OpenFile(ByVal args As Collections.ObjectModel.ReadOnlyCollection(Of String))

        Try

            RichEditControl1.LoadDocument(args)
            textpanel.Dock = DockStyle.Fill
            textpanel.BringToFront()
        Catch
            Forms.MessageBox.Show("Error opening selected file")
        End Try
    End Sub

Open in new window


I get the "Error opening selected file" message. Am I missing something?
0
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
What is getting passed in?...

Try this to understand what needs to be done with your arguments:

What is the exception?...
Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
            Dim args As New List(Of String)
            args.AddRange(e.CommandLine.ToArray)
            For i As Integer = 0 To args.Count - 1
                MessageBox.Show(i & ": " & args(i))
            Next
        End Sub

Open in new window

0
 
Bob LearnedConnect With a Mentor Commented:
You aren't looking at the exception in the Catch block, so you have no idea what the real problem.  My guess is the args is a collection, and not a single string argument, which may be a problem for the RichEditControl.
0
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Also, note that I used "e.CommandLine" in the StartupNextInstance() event.

You had "Environment.GetCommandLineArgs()" which only gets the arguments for the FIRST instance (not subsequent instances).
0
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Hey Bob!...haven't seen ya in awhile.  =)
0
 
SkwerlzAuthor Commented:
K, I copied your script. placed as such:
    Partial Friend Class MyApplication

        Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
 Dim args As New List(Of String)
            args.AddRange(e.CommandLine.ToArray)
            For i As Integer = 0 To args.Count - 1
                MessageBox.Show(i & ": " & args(i))
            Next

        End Sub
    End Class


End Namespace

Open in new window


Believe it or not, doesn't even show the message box. I did play around with e.command before I posted that last bit. I copied directly from the msdn page on startupnextinstance here
MSDN StartUpNextInstance
 I have done a lot of googling as well, not having much luck in getting the file path. Don't know if you are familiar with the devexpress winform components. I'm assuming you are, but the commandline I'm looking for is passed when the file is double clicked in explorer. <-- just to reiterate for those who are new to this thread.

The command line I'm looking for is "c:\folder\richtextfile.rtf"
Not trying to insult anyone's intelligence, just trying to be as clear as possible on my question.

Thanks everyone for the replies. We will get this!!
Skwerlz
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Did you set the "make single instance application" box in Project --> Properties?

Not sure if the DexExpress components are interfering with the application events somehow...never used them.
0
 
SkwerlzAuthor Commented:
Yeah, it is set to single instance. In the last few attempts I haven't even made reference the dev express components. I have just been using the message boxes to display any info I can get. I even tried an args count and it returns zero. It's wierd because through the various codes I have tried it has showed that the startupnext instance is catching something and even activating message boxes on the proper forms, but I don't seem to be getting any command lines or args passed to the program.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Is the first instance being hosted by the IDE?...or is it running normally?  Not sure if that has an affect as I've never tried it that way.

Does the first file association open up the program and get received properly?

Describe how you are testing the system...
0
 
CodeCruiserCommented:
I use DevExpress components and I those have nothing to do with this. Either the file association is not working so explorer is not passing the argument or something else.  This is a vital question:

>Does the first file association open up the program and get received properly?
0
 
SkwerlzAuthor Commented:
In order to test the program correctly I publish it, install then run the tests. at least for file association I have been because of the args.

File association is set. so far if the program is not running and I double click an associated file it starts up my prog and porperly loads the file.
    Private Sub RibbonForm1_Load_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
                


        Try
            If AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData IsNot Nothing _
      AndAlso AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData.Length > 0 Then

                RichEditControl1.LoadDocument(AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData(0))
                textpanel.Dock = DockStyle.Fill
                textpanel.BringToFront()
            End If
        Catch
            Forms.MessageBox.Show(MessageBoxImage.Error, "Error opening selected file")
        End Try
    End Sub

Open in new window



I have no problems with that. Its getting a double clicked file to pass the file path when there is a running instance. I'm fairly new to dealing with arguments and command lines.
It seems wierd that I can't seem to get anything passed through. It has to be getting something because it fires the Startupnextinstance.  I have got message boxes to launch directly from app events as well as from a designated form. I have tried arg counts which returned zero, I have tried e.command, my.application.commandlineargs, etc. I just need to see what is being sent somehow.
0
 
SkwerlzAuthor Commented:
Anybody?
0
 
SkwerlzAuthor Commented:
I still have not found an answer for this issue
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Have you tried with a NEW, BLANK project just to see if you can get it to work there?  This may tell if it's just something about your particular project that is causing the issue...
0
 
SkwerlzAuthor Commented:
this is tough because I am so far into the project it could be a number of things. I will try and post any findings.
0
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Understood.  Since your project is well underway it is next to impossible for us to troubleshoot from our end without any exceptions being thrown.

I would start bare bones with just the Application Events and verify that it works as expected passing filenames.  Then start adding other features and testing until it fails...

It'll be a pain in the butt I'm sure.
0
 
SkwerlzAuthor Commented:
Thanks for the input. I will update on progress
0
 
SkwerlzAuthor Commented:
no prohress yet. Although I am getting the trigger to send a messagebox when an associated file is double clicked while running. Still no args passed.
0
 
SkwerlzAuthor Commented:
Never found the correct answer. Got close with the suggestions of everyone, but had to scrap the project due to time constraint
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.