Aplikacje Metro - JavaScript: drukowanie (w tym aplikacje dla urządzeń), obsługa zdarzeń AutoPlay, kojarzenie pliku lub protokołu z aplikacją, Live Connect API (łatwa integracja z Hotmail, SkyDrive i Windows Live Messenger).
Printing
The new print features also allow IHVs to customize the print experience and to provide support for advanced scenarios.
If you are using a touch screen, tap the right side of the screen. If you are using a mouse, hover over the right side of the screen.
function printButtonClick() {
try {
// First, register the print contract
var pm = Windows.Graphics.Printing.PrintManager.getForCurrentView();
pm.onprinttaskinitializing = initializePrintTask;
Windows.Graphics.Printing.PrintManager.showPrintUI();
} catch (exception) {
sdkPrintSample.DisplayError(exception.message);
}
}
function previewButtonClick() {
try {
// First, register the print contract
var pm = Windows.Graphics.Printing.PrintManager.getForCurrentView();
pm.onprinttaskinitializing = initializePrintTask;
// Add custom code here to perform tasks for
// servicing a click of the preview button
} catch (exception) {
sdkPrintSample.DisplayError(exception.message);
}
}
function initializePrintTask(ev) {
// Create a print task, then initialize it with standard settings
var doc = document.getHTMLPrintDocument();
var printTask = ev.request.initializePrintTask(d, "Print Sample");
}
Formatting content for printing
// Style to prevent your chosen items from being printed.
// This can be used, for example, to prevent buttons from being printed.
<style media="print" type="text/css"> .noprint
{
display: none;
}
</style>
// Style to prevent your chosen items from being displayed on screen.
// These items can, however be displayed in a print preview window
// and even printed, using the appropriate code tied to a button.
<style media="screen" type="text/css"> .noscreen
{
display: none;
}
</style>Responding to a print event
// Variable to keep track of whether or not
// a print contract has been registered
var isPrintContractRegistered = false;
// Function to process the Print button click
function printEventsButtonClick() {
try {
// Configure the print events, match them with their event handlers
window.document.body.onbeforeprint = beforePrint;
window.document.body.onafterprint = afterPrint;
// Check to see if Print Contract is registered
if (isPrintContractRegistered) {
printViaShowPrintUI();
} else {
// There is no print contract, so use legacy print code
window.print();
}
} catch (exception) {
sdkSample.displayError(exception.message);
}
}
// Function to provide basic printing via PrintManager
function printViaShowPrintUI() {
Windows.Graphics.Printing.PrintManager.showPrintUI();
}
// Event handlers to handle onBeforePrint and onAfterPrint
var beforePrint = function () {
try {
// Custom code goes here for what to do before printing
sdkSample.displayStatus("Message from the beforePrint event handler.");
} catch (exception) {
sdkSample.displayError(exception.message);
}
};
var afterPrint = function () {
try {
// Custom code goes here for what to do after printing
sdkSample.displayStatus("Message from the afterPrint event handler.");
} catch (exception) {
sdkSample.displayError(exception.message);
}
};
Customization the Metro style app print dialog
You will programatically choose from the standard Microsoft print settings. In addition to choosing which of the available print settings you present to your users via the print dialog, this technique also allows you to re-order the print settings.
// Code to show how to programmatically choose from std print settings
function onDocRequestedCustom(ev) {
try {
var d = document.getHTMLPrintDocument();
var pt = ev.request.initializePrintTask(d, "Print Sample");
// First, clear the standard list of settings options
pt.options.displayedOptions.clear();
// Now populate list of settings options. Be aware that
// the order in which the append statements are listed,
// determines the order in which the options are displayed
pt.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.copies);
pt.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.orientation);
pt.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.mediasize);
pt.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.collation);
pt.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.duplex);
} catch (exception) {
sdkSample.displayError(exception.message);
}
}
// Command to call a function to initialize a print task
// and also to customize the print dialog
pm.onprinttaskinitializing = onDocRequestedCustom;
Guidance for Metro style apps for devices
Such an app provides a device-specific, supplementary experience for the user. This topic shows you what an enhanced experience looks like. For example, an app can replace the default Print Preferences experience that is provided with Windows with a customized experience. Another type of Metro style app for devices, called a notification, can be used by devices to alert the user or the app about device-related issues. When a Notification alerts a user, it uses a type of dialog called a toast.
Amelia creates her invitation, and then selects Print.
In the Print Dialog, Amelia selects More Settings, to see the current print preferences.
Without customization, this is the Windows-provided default Print Preferences dialog that Amelia would see.
In this customized and branded Metro style app for devices for the Print Preferences dialog, Amelia modifies the number of photos per page.
After modifying the number of photos per page, Amelia selects the Back arrow. This automatically saves the new settings or print preferences, and returns her to the Print Dialog.
Amelia can now verify her new print preferences before selecting Print.
When Amelia selects Print, the app she’s using receives a notification from the printer to indicate that the ink levels are low. The notification dialog is called a toast.
Amelia selects (or touches) the toast, and the next notification dialog shows her the particular ink cartridge or cartridges that have low ink. She selects Add to Cart to order replacements.
When Amelia adds the ink cartridge to her cart, the next notification dialog presents her with another screen that provides more information about the order that she is about to place. She reviews the information and selects Buy.
Amelia then selects or touches the Back arrow to return to the Print Dialog, where she can select Print to complete her printing task.
Do not [resent information that is not relevant to the task of setting print preferences. For example, do not provide information about how to clean the print heads.
After you call window.print(), check for any error messages, and handle them appripriately.
Do not try to customize your print experience to use the V3 print driver. Avoiding this practice ensures that your Metro style app works properly.
AutoPlay
AutoPlay enables you to provide your application as an option when a user connects a device to their computer. This includes non-volume devices such as a camera or media player, or volume devices such as a USB thumb drive, SD card, or DVD. AutoPlay also enables you to register your application as an option when users share files between two machines by using Proximity (tapping).
When a user connects a device, AutoPlay determines the type of device and raises either a device event for non-volume devices, or a content event for volume devices. You can register for the event that corresponds to your application by adding a Declaration in your application manifest for the specific event type. After you have built and deployed your application, AutoPlay recognizes the declaration for your application and includes it in the list of possible actions that a user can take to respond to that event. You can also perform an action when a user has received files that are shared by using Proximity (tapping). In this case, the files are placed in a temporary folder on the target computer and AutoPlay raises a content event based on the type of files shared.
AutoPlay events
- WPD\ImageSource - raised for cameras that are identified as Windows Portable Devices and offer the ImageSource capability
- CameraMemoryOnArrival - raised for a volume event where a /DCIM folder exists in the root of the volume, which is a standard for many cameras. For example, when a user takes a memory card from a camera and inserts it into their PC, AutoPlay will detect the /DCIM folder and raise the CameraMemoryOnArrival event.
- WPD\AudioSource - raised for media players that are identified as Windows Portable Devices and offer the AudioSource capability.
- WPD\VideoSource - raised for video cameras that are identified as Windows Portable Devices and offer the VideoSource capability.
- StorageOnArrival - raised when a drive or volume is connected to the computer (a connected flash drive or external hard drive). If the drive or volume contains a /DCIM folder in the root of the disk, the CameraMemoryOnArrival event is raised instead.
- ShowPicturesOnArrival - using photos from mass storage (legacy) and receiving photos with Proximity Sharing (tap and send). If a user has enabled Choose what to do with each type of media in the AutoPlay Control Panel, AutoPlay will examine a volume connected to the computer to determine the type of content on the disk. When pictures are found, ShowPicturesOnArrival is raised. When users send content with using proximity (tap and send), AutoPlay will examine the shared files to determine the type of content. If pictures are found, ShowPicturesOnArrival is raised.
- PlayMusicFilesOnArrival - using music from mass storage (legacy) and receiving music with Proximity Sharing (tap and send). If a user has enabled Choose what to do with each type of media in the AutoPlay Control Panel, AutoPlay will examine a volume connected to the computer to determine the type of content on the disk. When music files are found, PlayMusicFilesOnArrival is raised. When users send content with using proximity (tap and send), AutoPlay will examine the shared files to determine the type of content. If music files are found, PlayMusicFilesOnArrival is raised.
- PlayVideoFilesOnArrival - using videos from mass storage (legacy) and receiving videos with Proximity Sharing (tap and send). If a user has enabled Choose what to do with each type of media in the AutoPlay Control Panel,, AutoPlay will examine a volume connected to the computer to determine the type of content on the disk. When video files are found, PlayVideoFilesOnArrival is raised. When users send content with using proximity (tap and send), AutoPlay will examine the shared files to determine the type of content. If video files are found, PlayVideoFilesOnArrival is raised.
- MixedContentOnArrival - handling mixed sets of files from a connected device and handling mixed sets of files with Proximity Sharing (tap and send). If a user has enabled Choose what to do with each type of media in the AutoPlay Control Panel, AutoPlay will examine a volume connected to the computer to determine the type of content on the disk. If no specific content type is found (for example, pictures), MixedContentOnArrival is raised. When users send content with using proximity (tap and send), AutoPlay will examine the shared files to determine the type of content. If no specific content type is found (for example, pictures), MixedContentOnArrival is raised.
- PlayDVDMovieOnArrival, PlayBluRayOnArrival, PlayVideoCDMovieOnArrival, PlaySuperVideoCDMovieOnArrival - handle video from optical media
- PlayCDAudioOnArrival, PlayDVDAudioOnArrival - handle music from optical media
- PlayEnhancedCDOnArrival, PlayEnhancedDVDOnArrival - play enhanced disks
- HandleCDBurningOnArrival, HandleDVDBurningOnArrival, HandleBDBurningOnArrival - handle writeable optical disks
- UnknownContentOnArrival - handle any other device or volume connection. Raised for all events in case content is found that does not match any of the AutoPlay content events. Use of this event is not recommended. You should only register your application for the specific AutoPlay events that it can handle.
Open the Package.appxmanifest file and select the Capabilities tab. Select the Removable Storage and Picture Library Access capabilities, to give the application access to removable storage devices for camera memory, and access to the local Pictures library.
In the manifest file, select the Declarations tab. In the Available Declarations drop-down list, select AutoPlay Content and click Add. Select the new AutoPlay Content item that was added to the Supported Declarations list.
An AutoPlay Content declaration identifies your application as an option when AutoPlay raises an event. In the Launch Actions section, enter the following values for the first launch action: ContentEvent – CameraMemoryOnArrival, Verb – show, ActionDisplayName - Show Pictures.
The ActionDisplayName setting identifies the string that AutoPlay displays for your application. The Verb setting identifies a value that is passed to your application for the selected option. You can specify multiple launch actions for an AutoPlay event and use the Verb setting to determine which option a user has selected for your application. You can tell which option the user selected by checking the verb property of the startup event arguments passed to your application.
In the Launch Actions section for the AutoPlay Content item, click Add New to add a second launch action. Enter the following values for the second launch action: ContentEvent - CameraMemoryOnArrival, Verb - copy, ActionDisplayName - Copy Pictures Into Library.
In the Available Declarations drop-down list, select File Type Associations and click Add. In the Properties of the new File Type Associations declaration, set the Display Name field to AutoPlay Copy or Show Images and the Name field to image_association1. In the Supported File Types section, click Add New. Set the FileType field to .jpg. In the Supported File Types section, click Add New again. Set the FileType field of the new file association to .png. For content events, AutoPlay filters out any file types that are not explicitly associated with your application.
var filesDiv;
WinJS.Application.onmainwindowactivated = function (e) {
filesDiv = document.getElementById("files");
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.file) {
if (e.detail.verb === "show") {
// Call displayImages with root folder from camera storage.
displayImages(e.detail.files[0]);
}
else if (e.detail.verb === "copy") {
// Call copyImagesToLibrary with root folder from camera storage.
copyImagesToLibrary(e.detail.files[0]);
}
}
}
For the camera memory event, AutoPlay passes the root folder of the camera storage in the startup arguments that are passed to the application. You can retrieve this folder from the first element of the details.files property.
function displayImages(rootFolder) {
// Display images from first folder in root\DCIM.
rootFolder.getFolderAsync("DCIM").then(
function (dcimFolder) {
dcimFolder.getFoldersAsync().then(
function (cameraFolders) {
cameraFolders[0].getFilesAsync().then(
function (files) {
files.forEach(function (file) {
filesDiv.innerHTML += file.name;
displayImage(file);
});
});
});
});
}
function displayImage(file) {
try {
var element = document.createElement("img");
element.src = window.URL.createObjectURL(file, false);
element.height = 100;
element.width = 100;
filesDiv.appendChild(element);
filesDiv.innerHTML += "<br>";
}
catch (e) {
filesDiv.innerHTML += e.message;
}
}
function copyImagesToLibrary(rootFolder) {
try {
var now = new Date();
var folderName =
"Images " + now.toDateString() + " " + now.getHours() +
now.getMinutes() + now.getSeconds();
Windows.Storage.KnownFolders.
picturesLibrary.createFolderAsync(folderName).then(
function (imageFolder) {
// Copy images from first folder in root\DCIM.
rootFolder.getFolderAsync("DCIM").then(
function (dcimFolder) {
dcimFolder.getFoldersAsync().then(
function (cameraFolders) {
cameraFolders[0].getFilesAsync().then(
function (files) {
files.forEach(function (file) {
copyImage(file, imageFolder);
});
});
});
});
});
} catch (e) {
filesDiv.innerHTML = "Failed copy images.<br />" + e.message;
}
}
function copyImage(file, imageFolder) {
try {
file.copyAsync(
imageFolder, file.fileName,
Windows.Storage.NameCollisionOption.replaceExisting).then(
function (newFile) {
filesDiv.innerHTML += file.fileName + " copied.<br />";
});
} catch (e) {
filesDiv.innerHTML += "Failed to copy image.<br />" + e.message;
}
}
To run your application, insert a camera memory card or another storage device from a camera into your machine. If you do not have a camera memory card, you can use a flash drive as long as it has a folder named DCIM in the root, and the DCIM folder has a subfolder that contains images.
When files are shared using proximity, the Files property of the FileActivatedEventArgs object contains a reference to a root folder that contains all of the shared files.
Working with association launching
This topic shows how to serve as a default program for a file type.
The app receives activation events only for the file extensions listed in the AppXManifest.xml file.
<Extensions>
<Extension Category="windows.fileTypeAssociation">
<FileTypeAssociation Name="documenttypes">
<SupportedFileTypes>
<FileType>.alsdk</FileType>
</SupportedFileTypes>
</FileTypeAssociation>
</Extension>
</Extensions>
function onActivatedHandler(eventArgs) {
if (eventArgs.kind == Windows.ApplicationModel.Activation.ActivationKind.file)
{
// Handle file activation.
// The number of files received is eventArgs.files.size
// The first file is eventArgs.files[0].name
}
}
This topic shows how to serve as a default program for a protocol.
The app receives activation events only for the protocols listed in the AppXManifest.xml file.
<Extensions>
<Extension Category="windows.protocol">
<Protocol Name="alsdkjs" />
</Extension>
</Extensions>
function onActivatedHandler(eventArgs) {
if (eventArgs.kind == Windows.ApplicationModel.Activation.ActivationKind.protocol)
{
// Handle protocol activation.
// The received URI is is eventArgs.uri.rawUri
}
}
This topic shows how to launch the default program for a file.
Get the file.
First, get a Windows.Storage.StorageFile object for the file.
If the file is included in the package for your app, you can use the Package.installedLocation property to get a Windows.Storage.StorageFolder object and the Windows.Storage.StorageFolder.getFileAsync method to get the StorageFile object.
If the file is in a known folder, you can use the properties of the Windows.Storage.KnownFolders class to get a StorageFolder and the getFileAsync method to get the StorageFile object.
// Launch the file
Windows.System.Launcher.launchDefaultProgramForFile(file);
You can also use the launchDefaultProgramForFile(StorageFile, ProgramPickerOptions, Point) method to let the user pick the app to launch from the Open With dialog box.
This topic shows how to launch the default program for a protocol.
Create a Windows.Foundation.Uri object for the URI to launch.
// The URI to launch
var uriToLaunch = "http://www.bing.com";
// Create a Uri object from a URI string
var uri = new Windows.Foundation.Uri(uriToLaunch);
// Launch the URI
Windows.System.Launcher.launchDefaultProgram(uri);
This sample uses launchDefaultProgram(Uri, LaunchingOptions) to launch the URI created in step 1 with a warning.
// Launch the URI with a warning prompt
Windows.System.Launcher.launchDefaultProgram(uri, Windows.System.LaunchingOptions.displayUntrustedUriWarning);
You can also use the launchDefaultProgram(Uri, ProgramPickerOptions, Point) method to let the user pick the app to launch from the Open With dialog box.
Working with web services
Live Connect enables your Metro style apps to work with info in Hotmail, SkyDrive, and Windows Live Messenger. How to add the Live Connect sign-in control to your apps. The sign-in control makes it easy to prompt users to sign in with their Microsoft account and allow your apps to work with their info.
Live Connect APIs
Identity
- Personalization - enable a user with a Microsoft account to sign in to an app, personalize the user's experience with that app, and easily register a user with that app.
- Profiles - work with a user's profile info.
Hotmail
- Contacts - work with info about a user's Hotmail contact and friend entries.
- Calendars - work with info in a user's calendars and calendar events.
SkyDrive
- Files, media, and more - work with a SkyDrive user's documents and photos in the cloud, to enable file browsing and sharing.
Messenger
- Instant messaging - exchange instant messages between Messenger users.
- Users and buddies - get a Messenger user's info, and info for his or her Messenger buddies—things like their friendly names, presence info, and status messages.
- Status updates - update a user's status message
Microsoft Connect website for Live Connect
User can sign in with a Microsoft account instead of with the local account. When this happens, if your apps use the Live Connect APIs, they can automatically detect that the user has already signed in and not require him or her to sign in again.
Before your app can work with info in services like Hotmail and SkyDrive , one thing it needs is a registered package name. The registered package name uniquely identifies your app to Live Connect. You can get a registered package name for your app at the Live Connect app management site for Metro style apps (https://manage.dev.live.com/Build).
Adding a Live Connect sign-in control
For Metro style apps using JavaScript, you use the WL.ui method to show and use this sign-in control.
c.d.n
Brak komentarzy:
Prześlij komentarz