Solved

Vb.net file association in running inctance

Posted on 2011-02-15
24
1,393 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
  • 11
  • 9
  • 2
  • +2
24 Comments
 
LVL 85

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 126 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 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 312 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
 
LVL 16

Assisted Solution

by:ToddBeaulieu
ToddBeaulieu earned 126 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 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 312 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 62 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 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 312 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 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 312 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 85

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

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 85

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 85

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 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 312 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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

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…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

760 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now