Tym razem uprawnienia dla urządzeń, enumeracja urządzeń oraz wykrywanie wśród nich zmian oraz drukowanie.
Podobnie jak ostatnim razem bez diametralnych zmian w stosunku do wersji Developer Preview. Pomijając niewielkie zmiany w API uwagę zwracają bardziej zaawansowane możliwości drukowania - konfiguracja standardowych parametrów wydruku oraz tworzenie własnych, własne szablony wydruku w HTML i JS zgodne z szablonami dla Internet Explorer … 5.5 i … oczywiście nowszych wersji (obok innych możliwości tj. XAML i Direct 2D), obsługa zakresu stron.
JS
Integrating devices, printers, and sensors
Enabling and disabling device capabilities
Device capabilities:
- Location
- Microphone
- Proximity
- Removable Storage
- Text Messaging
- Webcam
Note that some types of devices, such as printers and sensors, don't need to be declared in the app manifest.
Enumerating devices
How to retrieve additional properties for a device or PnP object
By default, findAllAsync and createWatcher return DeviceInformation objects have the following properties:
- Id - Not applicable. This property is the identity of the object.
- Name - System.ItemNameDisplay
- IsDefault - System.Devices.IsDefault
- IsEnabled - System.Devices.InterfaceEnabled
- EnclosureLocation - System.Devices.PhysicalDeviceLocation
How to display a device icon
Use getThumbnailAsync to get a photorealistic icon for the device. Use getGlyphThumbnailAsync to get a Metro style glyph for the device.
Printing
Print using the Devices Charm
(function () {
"use strict";
var app = WinJS.Application;
// This function responds to all application activations.
app.onactivated = function (eventObject) {
if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
//Register for print contract
var printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
printManager.onprinttaskrequested = onPrintTaskRequested;
WinJS.UI.processAll();
}
};
app.start();
// Print event handler for printing via the PrintManager API.
//printEvent contains the print task request object
function onPrintTaskRequested(printEvent) {
printEvent.request.createPrintTask("Print Sample", function (args) {
args.setSource(MSApp.getHtmlPrintDocumentSource(document));
});
}
})();
How to print using an in-app print button
(function () {
"use strict";
var app = WinJS.Application;
// This function responds to all application activations.
app.onactivated = function (eventObject) {
if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
//Register for print contract
var printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
printManager.onprinttaskrequested = onPrintTaskRequested;
//Add event handler for Print button click
document.getElementById("printButton").addEventListener("click", printButtonClick, false)
WinJS.UI.processAll();
}
};
app.start();
// Function to process the print button click
function printButtonClick() {
Windows.Graphics.Printing.PrintManager.showPrintUIAsync();
}
//Print event handler for printing via the PrintManager API.
//printEvent contains the print task request object
function onPrintTaskRequested(printEvent) {
printEvent.request.createPrintTask("Print Sample", function (args) {
args.setSource(MSApp.getHtmlPrintDocumentSource(document));
});
}
})();
How to change default settings in Metro style print window
By default, the print window shows the following settings:
- Number of copies
- Orientation
- Color
In addition to the preceding settings, Windows has several other common printer settings that developers can add to the print window. These are the other common settings:
- Paper size
- Print duplex
- Collation
- N-up
- Media type
- Paper sources
- Print quality
- Stapling
- Hole punching
- Binding
// Print event handler for printing via the PrintManager API.
// printEvent contains the print task request object
function onPrintTaskRequested(printEvent) {
var printTask = printEvent.request.createPrintTask("Print Sample", function (args) {
args.setSource(MSApp.getHtmlPrintDocumentSource(document));
});
// Enumerate the printer settings you want to show.
// They appear in the print window in the same order
// that you list them here
printTask.options.displayedOptions.clear();
printTask.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.copies);
printTask.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.mediaSize);
printTask.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.orientation);
printTask.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.duplex);
//You may even preset the values on a printer setting
printTask.options.mediaSize = Windows.Graphics.Printing.PrintMediaSize.northAmericaLegal;
};
How to add custom settings to Metro style print window
How to add app-specific settings to the print window, using a custom print template.
function onPrintTaskRequested(printEvent) {
// Register print contract with a custom print template
var printTask = printEvent.request.createPrintTask("Print Sample", function (args) {
args.setSource(MSApp.getHtmlPrintDocumentSource(document, "ms-appx:////customPrintTemplate.htm"));
});
// Retrieve the advanced Print Task Options
var printDetailedOptions = Windows.Graphics.Printing.OptionDetails.PrintTaskOptionDetails.getFromPrintTaskOptions(printTask.options);
// Choose the printer options to be shown.
// The order in which the options are appended determines the order in which they appear in the UI
printDetailedOptions.displayedOptions.clear();
printDetailedOptions.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.copies);
printDetailedOptions.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.orientation);
printDetailedOptions.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.colorMode);
// Create a new list option
//This setting will have the label "Content to print". The ID is "PageContent"
//This setting will show three options - "Pictures and text", "Pictures only", and "Text only"
var pageFormat = printDetailedOptions.createItemListOption("PageContent", "Content to print");
pageFormat.addItem("PicturesText", "Pictures and text");
pageFormat.addItem("PicturesOnly", "Pictures only");
pageFormat.addItem("TextOnly", "Text only");
// Add the custom option to the option list
printDetailedOptions.displayedOptions.append("PageContent");
}
The preceding code makes reference to a Custom Print Template (Beyond Print Preview: Print Customization - od IE 5.5, także najnowsze) in the onPrintTaskRequested() function. A Custom Print Template enables developers to customize the print settings in the Metro style Print window, and to update the preview layout anytime that the print settings change.
<HTML XMLNS:IE>
<HEAD>
<?IMPORT NAMESPACE="IE" IMPLEMENTATION="#default">
<STYLE TYPE="text/css">
.lorstyle
{
width:6.5in;
height:9in;
margin:0.5in;
background:white;
}
.pagestyle
{
width:8.5in;
height:11in;
background:white;
border-left:0 solid black;
border-top:0 solid black;
border-right:0 solid black;
border-bottom:0 solid black;
margin:0in;
}
</STYLE>
<SCRIPT LANGUAGE="JavaScript">
/// JavaScript code goes here from Step 5.5 and its sub steps
/// between the <script> and </script> tags
</SCRIPT>
// ## Content ##
<IE:TEMPLATEPRINTER ID="printer"/>
</HEAD>
<BODY ONLOAD="init()">
<DIV ID="pagecontainer">
<!-- Dynamically created pages go here-->
</DIV>
</BODY>
</HTML>
The TemplatePrinter element is the print template’s interface to the printer and to the printer settings.
<SCRIPT LANGUAGE="JavaScript">
var oPageStyleClass;
var oLorStyleClass;
var iNextPageToCreate = 1;
var loadFirstPageComplete = false;
var pageWidth = 0;
var pageHeight = 0;
var pageContent_last = null;
function init() {
// Attach Metro Printing events
//Handle pagination events
printer.onpaginate = handlePaginate;
//Handle preview page requests
printer.onpreviewpage = handlePreviewPage;
//Handle print requests
printer.onprint = handlePrint;
//Handle PrintTaskOptions change event
printer.onprinttaskoptionchange = handlePrintTaskOptionChange;
//Handle close request
printer.onclose = handleClose;
oPageStyleClass = findStyleRule(".pagestyle");
oLorStyleClass = findStyleRule(".lorstyle");
// Set the page dimensions
setPageLayout();
}
</SCRIPT>
Szczegóły na How to add custom settings to Metro style print window
How to print alternate content that is not displayed
<head>
<!-- Define the content to print -->
<link rel="alternate" href="http://go.microsoft.com/fwlink/?linkid=240076" id="alternateContent">
</head>
(function () {
"use strict";
var app = WinJS.Application;
// This function responds to all application activations.
app.onactivated = function (eventObject) {
if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
//Register for print contract
var printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
// set the alternate content
document.getElementById ("alternateContent").setAttribute("media", "print");
printManager.onprinttaskrequested = onPrintTaskRequested;
WinJS.UI.processAll();
}
};
// Print event handler for printing via the PrintManager API.
//printEvent contains the print task request object
function onPrintTaskRequested(printEvent) {
printEvent.request.createPrintTask("Print Sample", function (args) {
args.setSource(MSApp.getHtmlPrintDocumentSource(document));
});
}
app.start();
}
)();
How to add Page Range setting to a Metro style print window
(function () {
"use strict";
var app = WinJS.Application;
var printTask = null;
var pageRangeEditVisible = false;
function onPrintTaskRequested(printEvent) {
// Register print contract with a custom print template
printTask = printEvent.request.createPrintTask("Print Sample", function (args) {
args.setSource(MSApp.getHtmlPrintDocumentSource(
document, "ms-appx:////customPrintTemplate.htm"));
});
// Retrieve the print task option details
var printDetailedOptions = Windows.Graphics.Printing.OptionDetails.PrintTaskOptionDetails.getFromPrintTaskOptions(printTask.options);
// Choose the printer options to be shown.
// The order in which the options are appended determines the order in which they appear in the UI
printDetailedOptions.displayedOptions.clear();
printDetailedOptions.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.copies);
printDetailedOptions.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.orientation);
printDetailedOptions.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.colorMode);
// Create a new list option
var pageRange = printDetailedOptions.createItemListOption("PageRange", "Page Range");
pageRange.addItem("PrintAll", "Print all");
pageRange.addItem("PrintSelection", "Print Selection");
pageRange.addItem("PrintRange", "Print Range");
// Add the custom option to the option list
printDetailedOptions.displayedOptions.append("PageRange");
// Create a new edit option
var pageRangeEdit = printDetailedOptions.createTextOption("PageRangeEdit", "Range");
// Register the handler for option change event
printDetailedOptions.onoptionchanged = onOptionsChangedScenario;
}
// Handles option changes
function onOptionsChangedScenario(optionsEvent) {
var optionId = optionsEvent.optionId;
var printDetailedOptions = Windows.Graphics.Printing.OptionDetails.PrintTaskOptionDetails.getFromPrintTaskOptions(printTask.options);
// Handles change in Page Range Options
if (optionId === "PageRange") {
var pageRange = printDetailedOptions.options.lookup(optionId);
if (pageRange.value === "PrintRange") {
// Add the custom option to the option list
printDetailedOptions.displayedOptions.append("PageRangeEdit");
pageRangeEditVisible = true;
}
else {
if (pageRangeEditVisible) {
printDetailedOptions.displayedOptions.removeAtEnd();
pageRangeEditVisible = false;
}
}
} else if (optionId === "PageRangeEdit") {
var pageRangeEdit = printDetailedOptions.options.lookup(optionId);
var pattern = /^\s*\d+\s*(\-\s*\d+\s*)?(\,\s*\d+\s*(\-\s*\d+\s*)?)*$/;
// Validate the page range edit string and set error text
if (!pattern.test(pageRangeEdit.value)) {
pageRangeEdit.errorText = "Invalid Page Range (eg: 1-3 , 5)";
}
else {
pageRangeEdit.errorText = "";
}
}
}
function initialize() {
// Add any initialization code here
}
})();
Szczegóły na How to add Page Range setting to a Metro style print window
Guidelines for developing print capable Metro style apps
However, you may find that different printing technologies are better for different things. While you may use HTML5 and JavaScript with a custom print template, you may find that the layout functionality of XAML printing is easier to manage. Or you may discover that you want to lay out the printed content pixel by pixel, for which the Direct2D print control provides richer support.
C#
Enumerating devices
Enumerating commonly used devices
void InterfaceClasses_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (InterfaceClasses.SelectedItem == PrinterInterfaceClass)
{
InterfaceClassGuid.Text = "{0ECEF634-6EF0-472A-8085-5AD023ECBCCD}";
}
else if (InterfaceClasses.SelectedItem == WebcamInterfaceClass)
{
InterfaceClassGuid.Text = "{E5323777-F976-4F5B-9B55-B94699C46E44}";
}
else if (InterfaceClasses.SelectedItem == WpdInterfaceClass)
{
InterfaceClassGuid.Text = "{6AC27878-A6FA-4155-BA85-F98F491D4F33}";
}
}
async void EnumerateDeviceInterfaces(object sender, RoutedEventArgs eventArgs)
{
EnumerateInterfacesButton.IsEnabled = false;
DeviceInterfacesOutputList.Items.Clear();
try
{
var selector = "System.Devices.InterfaceClassGuid:=\"" + InterfaceClassGuid.Text + "\"";
// + " AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True";
var interfaces = await DeviceInformation.FindAllAsync(selector, null);
OutputText.Text = interfaces.Count + " device interface(s) found\n\n";
foreach (DeviceInformation deviceInterface in interfaces)
{
DisplayDeviceInterface(deviceInterface);
}
}
catch (ArgumentException)
{
OutputText.Text = "Caught ArgumentException. Verify that you've entered a valid interface class GUID.";
}
EnumerateInterfacesButton.IsEnabled = true;
}
async void DisplayDeviceInterface(DeviceInformation deviceInterface)
{
var id = "Id:" + deviceInterface.Id;
var name = deviceInterface.Name;
var isEnabled = "IsEnabled:" + deviceInterface.IsEnabled;
var item = id + " is " + name + " and " + isEnabled;
DeviceInterfacesOutputList.Items.Add(item);
}
Printing
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class BlankPage : Page
{
private Windows.Graphics.Printing.PrintManager printManager;
private Windows.UI.Xaml.Printing.PrintDocument printDocument;
private List<UIElement> printPages = null;
public BlankPage()
{
this.InitializeComponent();
this.InitializePrinting();
}
private void InitializePrinting()
{
//Create new print document
printDocument = new PrintDocument();
printDocument.AddPages += new AddPagesEventHandler(printDoc_AddPages);
printDocument.Paginate += new PaginateEventHandler(printDoc_Paginate);
printDocument.GetPreviewPage += new GetPreviewPageEventHandler(printDoc_GetPreviewPage);
// Get the print manager.
printManager = PrintManager.GetForCurrentView();
printManager.PrintTaskRequested += printManager_PrintTaskRequested;
}
void printManager_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
PrintTask printTask = args.Request.CreatePrintTask("Print Page Title", GetPrintSource);
}
private void GetPrintSource(PrintTaskSourceRequestedArgs e)
{
e.SetSource(printDocument.DocumentSource);
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
await PrintManager.ShowPrintUIAsync();
}
void printDoc_GetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
printDocument.SetPreviewPage(e.PageNumber, printPages[e.PageNumber - 1]);
}
void printDoc_Paginate(object sender, PaginateEventArgs e)
{
if (printPages == null)
{
printPages = new List<UIElement>();
printPages.Add(this);
printPages.Add(PageContentPanel);
}
printDocument.SetPreviewPageCount(printPages.Count, PreviewPageCountType.Intermediate);
}
void printDoc_AddPages(object sender, AddPagesEventArgs e)
{
for (int i = 0; i < printPages.Count; i++)
{
printDocument.AddPage(printPages[i]);
}
printDocument.AddPagesComplete();
}
}
Zawartość stron z uwzględnieniem parametrów wydruku - How to print using an in-app print button
// Prepare the print content and set the page preview page count.
void Paginate(object sender, Windows.UI.Xaml.Printing.PaginateEventArgs e)
{
printPages = new List<UIElement>();
GetPrintPages(e.PrintTaskOptions);
printDocument.SetPreviewPageCount(printPages.Count,
Windows.UI.Xaml.Printing.PreviewPageCountType.Final);
}
// Create a printable version of the requested print range.
void GetPrintPages(Windows.Graphics.Printing.PrintTaskOptions options) { … }
Brak komentarzy:
Prześlij komentarz