Launching Files with Associated Programs in Windows 8.x and VB

Introduction

The Windows 8 infrastructure is quite different than any earlier Windows version. This makes doing ordinary tasks quite cumbersome as: 1) you have to learn an entire different way of doing things, and 2) you have different tools at your disposal. By tools I mean classes in the Windows 8.x API.

What we will do today is launch a separate application from your Windows 8.x Store project. I will also show you all the various options involved. Let us get started.

Design

Let’s get the design of our page out of the way first. Open Visual Studio 2013 and create a new VB.NET Windows Store project. Name it anything descriptive. Your design should resemble Figure 1, and the XAML code associated with it will more or less resemble the code segment after Figure 1.

Our Design
Figure 1Our Design

The Resulting XAML code:

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="File Association VB.NET Example" VerticalAlignment="Top" Margin="46,43,0,0" FontSize="36"/>
        <Button x_Name="btViewPref" Content="Open App With Launch Preference" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="324,209,0,0"/>
        <Button x_Name="btWarning" Content="Open App With Warning" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="430,140,0,0"/>
        <Button x_Name="btOpenWith" Content="Show Open With Dialog" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="209,140,0,0"/>
        <Button x_Name="btDefault" Content="Open Defualt App" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="24,140,0,0"/>
        <ComboBox x_Name="cbViewPref" HorizontalAlignment="Left" VerticalAlignment="Top" Width="269" Margin="27,212,0,0">
            <ComboBoxItem Name="DefaultSel" IsSelected="True">Default
            <ComboBoxItem Name="UseLess">UseLess
            <ComboBoxItem Name="UseHalf">UseHalf
            <ComboBoxItem Name="UseMore">UseMore
            <ComboBoxItem Name="UseMinimum">UseMinimum
            <ComboBoxItem Name="UseNone">UseNone
        </ComboBox>
        <TextBlock x_Name="tbStatus" HorizontalAlignment="Left" TextWrapping="Wrap" Text="Status Will Be Shown Here" VerticalAlignment="Top" Margin="27,291,0,0" FontSize="16"/>

    </Grid>

You might want to have a very close look at the ComboBox section, as it shows its items, with their names. We will need this later. By having a look at the design you may be able to grasp what we will try to do today.

Opening Default Apps

A default app is the app that is associated with the file you’re trying to open’s file type. For example: When you double click a .docx file Microsoft Word opens up. This is why Microsoft Word is associated with the .docx file extension. Another example is when you double click on a .txt file, Notepad opens up. We will launch a default app based on a certain file extension. For the purposes of this article I added a picture with .png format into my Assets folder of the project. Now we just need to launch it.

Add the variable declaration:

    Private strFile As String = "Assets\smallTile.png" 'File To Be Used

Put the next code under the Open Default App button:

    'Opens Default Associated App
    Private Async Sub btDefault_Click(sender As Object, e As RoutedEventArgs) Handles btDefault.Click

        'Get File To Launch
        Dim FileToLaunch = Await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(strFile)

        'Launch and Give Report Back
        Dim blnStatus As Boolean = Await Windows.System.Launcher.LaunchFileAsync(FileToLaunch)

        If blnStatus Then

            tbStatus.Text = "File Successfully Launched!"

        Else

            tbStatus.Text = "Problems Occurred"

        End If

    End Sub

We identify the file to open with the use of Windows.ApplicationModel.Package.Current.InstalledLocation. This gets the app’s installed location. We simply then, launch the file with the help of the LaunchFileAsync method of the Windows.System.Launcher namespace. Yes, we could have added the Namespace at the top as well, honestly, I forgot.

When run, it will open the default application that is associated with the .png file extension.

Open an Application with a Warning Message

Now, because Windows 8.x works and launches apps differently, it is always good to warn the user that the current application’s focus will be shifted to a new application. This is what we will do now with the following code under the Open App With Warning button:

    Private Async Sub btWarning_Click(sender As Object, e As RoutedEventArgs) Handles btWarning.Click

        'Get File To Launch
        Dim FileToLaunch = Await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(strFile)

        'Create Warning Prompt
        Dim loLaunchOptions = New Windows.System.LauncherOptions()
        loLaunchOptions.TreatAsUntrusted = True

        Dim blnStatus As Boolean = Await Windows.System.Launcher.LaunchFileAsync(FileToLaunch, loLaunchOptions)

        If blnStatus Then

            tbStatus.Text = "File Successfully Launched!"

        Else

            tbStatus.Text = "Problems Occurred"

        End If

    End Sub

We basically repeat the default button’s code here, with  two tiny changes. The first change is that we now have created a LauncherOptions object with the TreatAsUntrusted attribute set to true. This will cause the system to display a warning message similar to Figure 2. When we launch the app, we also specify the LauncherOptions object.

Warning Message
Figure 2Warning Message

Displaying the “Open With” Windows Dialog

Giving a user options is always a wonderful idea – but obviously only up to a point. This topic is just for illustration purposes. It is possible to show the Windows inherent Open With dialog. In older versions of the Windows Operating system this was quite a painful complicated process. I love it when complicated things become more available and easier for developers!

Add the following function:

    'Structure Location Of OPW Box
    Private Function GetOpenWitDlghPos(ScreenElement As FrameworkElement) As Windows.Foundation.Point

        'We Want To Display It Close To Our Button
        Dim ElementToTransform As Windows.UI.Xaml.Media.GeneralTransform = ScreenElement.TransformToVisual(Nothing)

        Dim ptLoc As Point = ElementToTransform.TransformPoint(New Point())

        ptLoc.Y = ptLoc.Y + ScreenElement.ActualHeight() 'Set Position

        Return ptLoc

    End Function

This function we will use with the following code (behind the Open With button):

    Private Async Sub btOpenWith_Click(sender As Object, e As RoutedEventArgs) Handles btOpenWith.Click
        'Get File To Launch
        Dim FileToLaunch = Await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(strFile)

        ' Calculate the position for the Open With dialog.
        Dim pOpenWithDialogPos As Point = GetOpenWitDlghPos(btOpenWith)

        'Set OPW Dialog Options
        Dim loLaunchOptions = New Windows.System.LauncherOptions()
        loLaunchOptions.DisplayApplicationPicker = True
        loLaunchOptions.UI.InvocationPoint = pOpenWithDialogPos
        loLaunchOptions.UI.PreferredPlacement = Windows.UI.Popups.Placement.Below

        ''Launch
        Dim blnStatus As Boolean = Await Windows.System.Launcher.LaunchFileAsync(FileToLaunch, loLaunchOptions)

        If blnStatus Then

            tbStatus.Text = "File Successfully Launched!"

        Else

            tbStatus.Text = "Problems Occurred"

        End If

    End Sub

What happens here? Well, the GetOpenWitDlghPos function calculates where we want to display the system’s Open With dialog. This code I saw on a Microsoft example and just had to share it with you, because it is funky, but was in C#. 🙁

After we have determined the precise location of the Open With dialog (which is directly below the Open With button), we launch the app with the selected Open With choice selected. Figure 3 shows what it will look like.

Open With dialog
Figure 3Open With dialog

Application View Modes

I repeat, apps work totally different in Windows 8. When a new app is launched, by default it gets placed above the previous app. But, what if we want to display the apps side by side? What if we want to Show more of one app and a bit less of another app? All this will be achieved with the Windows.UI.ViewManagement.ViewSizePreference, as illustrated in the next code segment:

    Private Async Sub btViewPref_Click(sender As Object, e As RoutedEventArgs) Handles btViewPref.Click

        ' Create File Picker To Srelect File
        Dim opOpen = New Windows.Storage.Pickers.FileOpenPicker()
        opOpen.FileTypeFilter.Add("*")

        'Get Selected File
        Dim SelFile As Windows.Storage.StorageFile = Await opOpen.PickSingleFileAsync()
        If (SelFile IsNot Nothing) Then

            'Determine Launch Parameters From the ComboBox
            Dim loLaunchOptions = New Windows.System.LauncherOptions()

            If DefaultSel.IsSelected = True Then

                loLaunchOptions.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.Default

            ElseIf UseLess.IsSelected = True Then

                loLaunchOptions.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseLess

            ElseIf UseHalf.IsSelected = True Then

                loLaunchOptions.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseHalf

            ElseIf UseMore.IsSelected = True Then

                loLaunchOptions.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseMore

            ElseIf UseMinimum.IsSelected = True Then

                loLaunchOptions.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseMinimum

            ElseIf UseNone.IsSelected = True Then

                loLaunchOptions.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseNone

            End If

            Dim blnStatus As Boolean = Await Windows.System.Launcher.LaunchFileAsync(SelFile, loLaunchOptions)

            If blnStatus Then

                tbStatus.Text = "File Successfully Launched!"

            Else

                tbStatus.Text = "Problems Occurred"

            End If

        Else

            tbStatus.Text = "Problems Occurred"

        End If

    End Sub

This code segment looks more intimidating than it is! It has all the same code we have been playing with all along, but now, we just have to determine which View option has been chosen in the ComboBox, then apply it to the launching app. Have a look into the ViewSizePreference enumeration to get a nicer idea; if you haven’t played around with it in your program yet!

Conclusion

Well, that wasn’t too tough now was it? With new technology comes new ways of thinking and new ways of achieving the same ultimate goal. Good luck and happy coding!

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read