Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Vb.net file association in running inctance

Posted on 2011-02-15
24
Medium Priority
?
1,418 Views
Last Modified: 2012-05-11
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

0
Comment
Question by:Skwerlz
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 9
  • 2
  • +2
24 Comments
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 34901164
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
 
LVL 16

Accepted Solution

by:
ToddBeaulieu earned 378 total points
ID: 34901181
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
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 936 total points
ID: 34901220
@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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 16

Assisted Solution

by:ToddBeaulieu
ToddBeaulieu earned 378 total points
ID: 34901279
Oh, that's interesting. Thanks!
0
 

Author Comment

by:Skwerlz
ID: 34902822
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
 

Author Comment

by:Skwerlz
ID: 34903072
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
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 936 total points
ID: 34903230
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
 
LVL 96

Assisted Solution

by:Bob Learned
Bob Learned earned 186 total points
ID: 34903237
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
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 936 total points
ID: 34903247
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
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 936 total points
ID: 34903251
Hey Bob!...haven't seen ya in awhile.  =)
0
 

Author Comment

by:Skwerlz
ID: 34912156
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 34912490
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
 

Author Comment

by:Skwerlz
ID: 34913496
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 34913515
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
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 34914444
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
 

Author Comment

by:Skwerlz
ID: 34915904
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
 

Author Comment

by:Skwerlz
ID: 34957315
Anybody?
0
 

Author Comment

by:Skwerlz
ID: 35047133
I still have not found an answer for this issue
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 35047141
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
 

Author Comment

by:Skwerlz
ID: 35047299
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
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 936 total points
ID: 35047321
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
 

Author Comment

by:Skwerlz
ID: 35058727
Thanks for the input. I will update on progress
0
 

Author Comment

by:Skwerlz
ID: 35134711
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
 

Author Closing Comment

by:Skwerlz
ID: 37232027
Never found the correct answer. Got close with the suggestions of everyone, but had to scrap the project due to time constraint
0

Featured Post

Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question