Launching a File in Windows Store Apps

Introduction

In this article I describe how to create a Windows Store App for launching a file using JavaScript. The default handler application for .jpg files is launched and displays in the foreground. This app is moved to the background. If there is no default handler for .jpg or the Launch Open With button is clicked an "Open With" dialog is displayed.

I assume you can create a simple Windows Store App using JavaScript. For more help visit Simple Windows Store Apps using JavaScript.

To start the creation of the app, add one JavaScript page by right-clicking on the js folder in the Solution Explorer and select Add > new item > JavaScript Page and then give an appropriate name. In the same way, add one HTML page to your project.

launching-file-in-windows-store-app.jpg

Write the following code in default.html:

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <title></title> 

    <link rel="stylesheet" href="//Microsoft.WinJS.1.0/css/ui-light.css" />

    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>

    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

    <link rel="stylesheet" href="/css/default.css" />

    <script src="/js/script1.js"></script>

    <script src="/js/default.js"></script>

</head>

<body role="application"style="background-color:darkkhaki">

    <center><div id="rootGrid">

        <div id="content">

            <h1 id="featureLabel"></h1>

            <div id="contentHost"></div>

        </div>

    </div></center>

</body>

</html>


Write the following code in default.js:

(
function () {

    "use strict";

    var AppTitle = "";

    var pages = [

        { url: "page.html" }

    ]; 

    function activated(e) {

        var url = null;

        var arg = null;

        if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.file) {

            url = pages[2].url;

            arg = e.detail.files;

        } else if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.protocol) {

            url = pages[3].url;

            arg = e.detail.uri;

        } else if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            url = WinJS.Application.sessionState.lastUrl || pages[0].url;

        }

        if (url !== null) {

            e.setPromise(WinJS.UI.processAll().then(function () {

                return WinJS.Navigation.navigate(url, arg);

            }));

        }

    }

    WinJS.Navigation.addEventListener("navigated", function (evt) {

        var url = evt.detail.location;

        var host = document.getElementById("contentHost");

        host.winControl && host.winControl.unload && host.winControl.unload();

        WinJS.Utilities.empty(host);

        WinJS.UI.Pages.render(url, host, evt.detail.state).done(function () {

            WinJS.Application.sessionState.lastUrl = url;

        });

    });

    WinJS.Namespace.define("Apps", {

        AppTitle: AppTitle,

        pages: pages

    });

    WinJS.Application.addEventListener("activated", activated, false);

    WinJS.Application.start();

})();


Write the following code in page.html:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

    <link rel="stylesheet" href="/css/launch-file.css" />

    <script src="/js/script.js"></script>

</head>

<body>

    <div data-win-control="Apps.pageInput">

        <button class="action" id="launchFileButton">Launch Default Handler</button>

        <button class="action" id="launchFileWithWarningButton">Launch with Warning</button>

        <button class="action" id="launchFileOpenWithButton">Launch Open With</button>

        <button class="action" id="pickAndLaunchFileButton">Pick and than Launch</button><br />

    </div>

    <div data-win-control="Apps.pageOutput">

    </div>

</body>

</html>


Write the following code in script.js:

(function () {

    "use strict";

    var page = WinJS.UI.Pages.define("page.html", {

        ready: function (element, options) {

            document.getElementById("launchFileButton").addEventListener("click", launchFile, false);

            document.getElementById("launchFileWithWarningButton").addEventListener("click", launchFileWithWarning, false);

            document.getElementById("launchFileOpenWithButton").addEventListener("click", launchFileOpenWith, false);

            document.getElementById("pickAndLaunchFileButton").addEventListener("click", pickAndLaunchFile, false);

        }

    });

    var fileToLaunch = "images\\1.jpg";

    function launchFile() {

        Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(fileToLaunch).done(

            function (file) {

                Windows.System.Launcher.launchFileAsync(file).done(

                     function (success) {

                         if (success) {

                             WinJS.log && WinJS.log("File " + file.name + " launched.", "sample", "status");

                         } else {

                             WinJS.log && WinJS.log("File launch failed.", "sample", "error");

                         }

                     });

            });

    }

    function launchFileWithWarning() {

        Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(fileToLaunch).done(

          function (file) {

              var options = new Windows.System.LauncherOptions();

              options.treatAsUntrusted = true;

              Windows.System.Launcher.launchFileAsync(file, options).done(

                           function (success) {

                               if (success) {

                                   WinJS.log && WinJS.log("File " + file.name + " launched.", "sample", "status");

                               } else {

                                   WinJS.log && WinJS.log("File launch failed.", "sample", "error");

                               }

                           });

          });

    }

    function launchFileOpenWith() {

        Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(fileToLaunch).done(

            function (file) {

                var options = new Windows.System.LauncherOptions();

                options.displayApplicationPicker = true;

                options.ui.selectionRect = getSelectionRect(document.getElementById("launchFileOpenWithButton"));

                options.ui.preferredPlacement = Windows.UI.Popups.Placement.below;

                Windows.System.Launcher.launchFileAsync(file, options).done(

                                   function (success) {

                                       if (success) {

                                           WinJS.log && WinJS.log("File " + file.name + " launched.", "sample", "status");

                                       } else {

                                           WinJS.log && WinJS.log("File launch failed.", "sample", "error");

                                       }

                                   });

            });

    }

    function pickAndLaunchFile() {

        if (Windows.UI.ViewManagement.ApplicationView.value === Windows.UI.ViewManagement.ApplicationViewState.snapped) {

            if (!Windows.UI.ViewManagement.ApplicationView.tryUnsnap()) {

                WinJS.log && WinJS.log("Unable to unsnap theApp.", "sample", "error");

                return;

            }

        }

        var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

        openPicker.fileTypeFilter.replaceAll(["*"]);

        openPicker.pickSingleFileAsync().done(

            function (file) {

                if (file) {

                    Windows.System.Launcher.launchFileAsync(file).done(

                        function (success) {

                            if (success) {

                                WinJS.log && WinJS.log("File " + file.name + " launched.", "sample", "status");

                            } else {

                                WinJS.log && WinJS.log("File launch failed.", "sample", "error");

                            }

                        });

                }

                else {

                    WinJS.log && WinJS.log("No file was picked.", "sample", "error");

                }

            });

    }

    function getSelectionRect(element) {

        var selectionRect = element.getBoundingClientRect();

 

        var rect = {

            x: getClientCoordinates(selectionRect.left),

            y: getClientCoordinates(selectionRect.top),

            width: getClientCoordinates(selectionRect.width),

            height: getClientCoordinates(selectionRect.height)

        };

 

        return rect;

    }

    function getClientCoordinates(cssUnits) {

        return cssUnits * (96 / window.screen.deviceXDPI);

    }

})();

Output:

launching-file-in-windows-store-apps.jpg

Summary

In this app I described launching a file in a Windows Store app using JavaScript. I hope this article has helped you to understand this topic. Please share if you know more about this. Your feedback and constructive contributions are welcome.

Up Next
    Ebook Download
    View all
    Learn
    View all