Professional Documents
Culture Documents
Table of Contents
Running
If the app running you get events, which you can access it in App.cs file
If you run another application the other apps goes to background and waits for use to switch
back to that app after certain time interval it moves to suspended state .These state consider as
the app going to terminate (closed) state. Same process goes on until the system encounters
low memory.
Suspended
When the application move to the background or the device enters to the low power state, the
application suspends automatically. While pushing the application to the background, the
system waits for few seconds to make sure that the user switch back to the application
immediately. After the few seconds time interval, the system automatically moves the
application to the suspended state.
Based on the system available memory, the system wants to keep a number of suspended apps
into the memory to make sure the user can quickly switch back to the application. The app
always resides in memory as long as your system has available memory to execute. If your
available memory is low, the system automatically removes the unused application from
memory.
We can resume a suspended application from background and bring it to the foreground thread.
During the state transition, it loads the application data if you already saved during the
suspension state.
There is no event handler with the app termination. We can check whether the app got
terminated earlier through the activation event.
Part 3: Writing Your First Windows 10 UWP App
In this part we are going to see how to create a new UWP project.
Lets start create new windows 10 Blank App template with C# as language and then deploy
to run the app on Local Machine and Windows Mobile Emulator
After Successful installation (If you face problem in installation contact me) .start Visual
Studio 2015 select new project to create new windows 10 application and name it as
HelloWorldWin10 or as your wish like shown below.
Click Ok to create new app. Now you can see your app likes below.
Open the Mainpage.Xaml file in Visual Studio and add TextBlock in the existing grid. Set the
Text property of the TextBlock to Hello World Windows 10 as like below code.
Now time to run the app, by default, you will see that the solution is set to Debug and the
platform is set to x86. The Start Debugging button will also be set to Local Machine by
default. x86 will work for both mobile emulator and local machine. If you want to run this on
the Windows Mobile device, you will have to set this as Mobile Emulator.
Click the Start Debugging button with the Local Machine option to deploy to run the app
on the local machine.
In design time itself you can see the different device view looks like the following:
Now see the output for different device deployment.
Windows 10 Mobile
Windows 10 Tab
Windows 10 Desktop
Note: For Source Code
https://gallery.technet.microsoft.com/How-to-develop-apps-for-869aaaaf
In this part we are going to see how to show a message dialog in your Windows 10 apps on
the Desktop and Mobile devices using C# and XAML. The MessageDialog class is available
in Windows 10. We now have a Universal Windows Platform (UWP).
Create new Windows 10 UWP app and name it as you wish. Now go to Mainpage.Xaml and
paste the following XAML code to create a button for showing message dialog.
Create an instance of the MessageDialog with the Message and Title if required.
UICommands are added to the commands collection of the dialog. Default Command index is
set to 0 for (Yes) button to invoke user hit the enter key and the Cancel Command index is set
to 1 for (No) button to invoke user hit the Escape or No button.
Use ShowAsync() method to show the dialog and check the result containing command id
and perform the yes or no task.
Now run your app with Local Machine, Mobile and Simulator to see the output as in the
following image.
Local Machine
Mobile
Simulator
You can put any control that you like into the app bar.
<Page.TopAppBar>
<AppBar>
<StackPanel Orientation="Horizontal">
<AppBarButton Name="Button3" Icon="Add" Label="Add"></AppBarButton>
<AppBarButton Name="Button4" Icon="Remove" Label="Remove"></AppBarButton>
</StackPanel>
</AppBar>
</Page.TopAppBar>
<Page.BottomAppBar>
<AppBar IsOpen="True" IsSticky="True">
<StackPanel Orientation="Horizontal">
<AppBarButton Name="Button1" Icon="Add" Label="Add"></AppBarButton>
<AppBarButton Name="Button2" Icon="Remove" Label="Remove"></AppBarButton>
</StackPanel>
</AppBar>
</Page.BottomAppBar
Full source code looks like below
<Page
x:Class="AppBarDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppBarDemo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.TopAppBar>
<AppBar>
<StackPanel Orientation="Horizontal">
<AppBarButton Name="Button3" Icon="Add" Label="Add"></AppBarButton>
<AppBarButton Name="Button4" Icon="Remove" Label="Remove"></AppBarButton>
</StackPanel>
</AppBar>
</Page.TopAppBar>
<Page.BottomAppBar>
<AppBar IsOpen="True" IsSticky="True">
<StackPanel Orientation="Horizontal">
<AppBarButton Name="Button1" Icon="Add" Label="Add"></AppBarButton>
<AppBarButton Name="Button2" Icon="Remove" Label="Remove"></AppBarButton>
</StackPanel>
</AppBar>
</Page.BottomAppBar>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Grid>
</Page>
You can minimize and maximize the app bar by default using the IsOpen="True"
IsSticky="True".
To minimize the app bar set IsOpen property to false, by default it will be false.
You can create the App Bar using C# code also using the following code:
Now run the app and see the output like below
Part 7: Change Apps Title Bar Colour and Enable
Back Button In Windows 10 UWP
In this part we are going to see how to change the default application title bar colour in
windows 10 UWP.
In Windows 10 by default the white title bars is available for all apps, sometimes we need to
change for better UI. Using UI ViewManagement class we can get the application UI
properties. So, I am going to get the title bar properties and change the colour using the
following code.
appView.TitleBar.BackgroundColor = Colors.LightBlue;
appView.TitleBar.ButtonBackgroundColor = Colors.LightBlue;
appView.TitleBar.ForegroundColor = Colors.White;
appView.TitleBar.ButtonForegroundColor = Colors.White;
Place this code in app launching event in App.xaml.cs file as in the following code.
Full code looks like the following code
Now run the app and see the title bar it looks like the following image.
In Windows 10 UWP the back button is disabled by default. If you need back button in the
application title bar you need to enable it. I will show how to enable this button.
Firstly, get the current view and enable the back button.
Now create event handler for handling the back button click.
view.BackRequested += View_BackRequested;
Add the following method to handle the back button click.
private void View_BackRequested(object sender, BackRequestedEventArgs e)
{
//do your task
}
Now run the app and see the output looks like the following image.
In this part we are going to see how to create Split View/Hamburger menu in Windows UWP
10 app.
The new control SplitView added in Windows 10 and are used to display side menu. Many of
them called IT hamburger menu. Two things we need to know Pane and Content.
Pane
Content
<SplitView>
<SplitView.Pane>
Using IsPaneOpen property you can set true or false, true for open and false to close.
Now create a new Windows 10 project and give proper name. After that open
your Mainpage.xaml and you can see the empty Grid control as in the following screenshot
</StackPanel>
</SplitView.Pane>
<SplitView.Content>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="Hamburger Menu Demo" TextAlignment="Center"
VerticalAlignment="Center"></TextBlock>
</Grid>
</SplitView.Content>
</SplitView>
In the above code we are creating the button in menu and styling to hamburger menu. We
dont need to add icons for button, just change the Font family to Segoe MDL2 Assets and
set the content (cheat code) as your wish to see more icons cheat sheet codes.
For example, I set the content as &#E700; and it shows like the following image.
Now you can create button as your need here I create 4 button for sample.
Finally go to code behind page and I have one button click event to close and open the split
view. In handler we simply want to set pane to closed if it is open and vice versa like the
following code
In this part we are going to see how to show email and SMS compose task to send an email
and SMS in windows 10.
Create new Windows 10 project.
Now create two button one id for send email and one is for send SMS.
To send E-mail
First we are going to see how to send email .Write the below code
You can attach files also while sending email to attach the files write the below code before
compose the email task.
var stream =
Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(attachment);
To send SMS
To send an SMS write the below code
private async void ComposeSMS(Contact toContatc, string message)
{
var chatMessage = new Windows.ApplicationModel.Chat.ChatMessage();
chatMessage.Body = message;
var phone =
toContatc.Phones.FirstOrDefault<Windows.ApplicationModel.Contacts.ContactPhone>();
chatMessage.Recipients.Add(phone.Number);
await
Windows.ApplicationModel.Chat.ChatMessageManager.ShowComposeSmsMessageAsync(c
hatMessage);
}
In this part we are going to see how to use map control and get the current GPS C0-ordinates
street address in windows 10 UWP app.
Create new Windows 10 project and choose the map control from toolbox list.
Geo Location API allows easy to access a devices current location. Here we will see how to
get the longitude and latitude co-ordinates of the device.
Firstly, enable the location capabilities to allow the device to access the location like the
following screen.
using Windows.Devices.Geolocation;
using Windows.Services.Maps;
Create new instance for Geolocator using that we can retrieve the position of our device.
Then add the location coordinates points to our map control
Write the below code to set your position to the map control.
var geolocator = new Geolocator();
var position = await geolocator.GetGeopositionAsync();
mymap.Center = position.Coordinate.Point;
mymap.ZoomLevel = 15;
Set the map zoom level according to your needs and you will get the co-ordinates of the
current position.
Next we are going to get the current street address of the position using the coordinates.
BuildingFloor
BuildingName
BuildingRoom
BuildingWing
Continent
Country
CountryCode
District
FormattedAddress
Neighborhood
PostCode
Region
RegionCode
Street
StreetNumber
Town
}
else
{
dialog.Content = "Not Found";
}
Now run the app and see the output like below screen.
}
}
}
Now run the app and show the output looks like below.
openPicker.ViewMode = PickerViewMode.Thumbnail;
Then set the suggested location as your wish I am going to set default location as picture
library.
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
We need to add FileTypeFilter, mandatory fields you should add. It requires at least
One type.
The FileTypeFilter is a readonly collection. We would be able to add values.
Here I am setting filter type for png and jpg images.
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".png");
Finally we are going to show the file picker dialog as like below code and we have the option
to select sing or multiple file selection
Finally we are going to set the selected image stream to empty image control.
if(file!=null)
{
if(file!=null)
{
Finally run your app and show the output like below
For Source Code
Part 13: Pick text file in windows 10
In this part we are going to see the how to open text file using FileOpenPicker in Windows 10
application
In Windows 10 we have OpenFileDialog which opens a dialog to pick the files. Here we are
going to pick the text file in Windows 10.
Create new Windows 10 project and create a button and image control to perform File Picker
operation.
Firstly, create a new instance for FileOpenPicker as in the following code snippet:
FileOpenPicker openPicker = new FileOpenPicker();
Next, we have to set file picker ViewMode, you could ignore this, but if you would like to
add, there are two options, such as List and Thumbnail. Here I will set thumbnail.
openPicker.ViewMode = PickerViewMode.Thumbnail;
Then set the suggested location as you wish. I am going to set default location as document
library.
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
We need to add FileTypeFilter; it is a mandatory fields that you should add. It requires at
least one type.
The FileTypeFilter is a readonly collection. We would be able to add values.
Here I am setting filter type for .txt files.
openPicker.FileTypeFilter.Add(".txt");
Finally, we are going to show the file picker dialog as in the following code snippet and we
have the option to select single or multiple file selection
StorageFile file = await openPicker.PickSingleFileAsync();
Finally, we are going to read the selected file using stream and assign it to textblock.
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
using (StreamReader reader = new StreamReader(stream.AsStream()))
{
textBlockShow.Text = reader.ReadToEnd();
}
if (file != null)
{
}
}
Now run debug and run the app and see the output like below.
Part 15: Drag and Drop functionality instead of File
Picker in Windows 10
In this part we are going to see drag-and-drop functionality in windows 10 UWP app.
In Windows 10 platform, a new drag-and-drop functionality was introduced to Windows
Universal apps for scenarios such as dragging image or document from your local machine
straight into your app. It allows us developers to support more intuitive experiences. Drag and
drop is a good way to transfer data within an application or between applications using a
standard gesture.
Lets see how simple it is to drag and drop image from your local system desktop into your
Windows 10 Universal apps.
Steps:
Create new Windows 10 blank project and give suitable name.
Open your MainPage.XAML page and go to xaml code area in that create one StackPanel
and allow drop property to true. Attach an event handler to Drop and DropOver event. Which
will be used to handle an event of dropping image or document on the stackpanel. DropOver
will be used to allow image copying while it's dragged over the stackpanel.
Add an Image object inside to show the image which was dropped.
Full source code looks like the following,
Now go to code behind page and write the below code in drop and dragover event handler.
When image is being dragged over the stackpanel the DragOver event handler will be fired in
that event. I am going to allow copying the dragged image.
When the photo gets dropped the drop event will be fired and here I will take it from the
StorageItems collection and set the Source for dragedImage image.
You can set the Caption also for better user experience for that change the dragover event
code like the following,
In this part we are going to learn how to create local DB for windows 10 app and perform the
operation CRUD (Create Read Update and Delete) operation in Windows 10 Data Base.
See the step by step implementation.
Introduction
<Grid Background="#FFF589E2">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Button x:Name="CreateDBbutton" Grid.Row="0" Content="Create Local Database"
HorizontalAlignment="Center" VerticalAlignment="Top" Click="button_Click"/>
<Button x:Name="create" Grid.Row="1" Content="Create New Students"
HorizontalAlignment="Center" Click="create_Click"></Button>
<Button x:Name="read" Grid.Row="2" Content="Read Students List" Width="300"
Click="read_Click" HorizontalAlignment="Center"></Button>
<Button x:Name="update" Grid.Row="3" Content="Update Details" Width="300"
Click="update_Click" HorizontalAlignment="Stretch"></Button>
<ListView x:Name="allstudents" HorizontalAlignment="Stretch" Grid.Row="4" >
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="ee" Text="{Binding Name}" FontSize="14"></TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
Now write the below code in your corresponding button click events.
I am going to create one Student DB with Students Table with id,Name,Address and Mobile
so first design the table as like below
public class Students
{
[SQLite.Net.Attributes.PrimaryKey, SQLite.Net.Attributes.AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Mobile { get; set; }
public Students()
{
}
public Students(string name, string address, string mobile)
{
Name = name;
Address = address;
Mobile = mobile;
}
}
Create DB
public static void CreateDatabase()
{
var sqlpath =
System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,
"Studentdb.sqlite");
}
}
Insert New Student details
public void Insert(Students objContact)
{
var sqlpath =
System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,
"Studentdb.sqlite");
}
}
}
}
Delete specific student
In this part we will see how to consume a REST service in Windows 10. Before that we will
introduce REST services.
REST is a resource that implements a uniform interface using standard HTTP GET, POST,
PUT methods that can be located by URI.
Windows 10 UWP supports basic get and post web requests using the following two APIs:
System.Net.Http.HttpClient
Windows.Web.Http.HttpClient.
The System.Net.Http.HttpClient was introduced in .NET 4.5. In Windows 10 this API has
changed to top layer of Windows.Web.Http.HttpClient. The supported OS and programming
languages are as follows:
Both of this APIs are available in UWP. Select which one you need.
If you are going to develop native UI or pass specific SSL certificates for Authentication then
useWindows.Web.Http.HttpClient API.
If you are going to develop app with cross platform such as iOS, Android, then
useSystem.Net.Http.HttpClient. This API sppports Xamarin IOS and Android development.
Here, I will create runtime JSON data using dynamic and ExpandoObject, using this you can
create JSON string at runtime instead of creating classes.
Json.Net are used to serialize the runtime dynamic object values to JSON data.
Now run the app and see the excepted out put
Note:
For source code
Microsoft finally released live streaming API supports in UWP Windows 10. Before that we
need third party API Windows Phone Streaming Media Assistance. But it will arrive in UWP.
This namespace definition support many kinds of different adaptive streaming protocols, such
as Http Live Streaming or HLS is a protocol for streaming media content that is segmented
into several small files, each of them in different sizes and qualities to enable the content
disseminating an adaptive rate depending on the quality of the connection.
This returns AdaptiveMediaSourceCreationResult which includes the source and whether the
manifest was able to be downloaded or what error occurred. Remember that you enabled the
InternetClient capability in your appxmanifest file.
Create new Windows 10 project and go to MainPage.xaml page design view to design.
Add Media control to play the streamed videos and use the following code to design media
control:
<Grid>
<MediaElement x:Name="liveMedia" />
</Grid>
Next add two app bar controls to Play and Pause the streaming.
<Page.BottomAppBar>
<AppBar IsOpen="True">
<StackPanel Orientation="Horizontal">
<AppBarButton Name="playBtn" Click="playBtn_Click" Icon="Play"
Label="Play"></AppBarButton>
<AppBarButton Name="pausBtn" Click="pausBtn_Click" Icon="Pause"
Label="Pause"></AppBarButton>
</StackPanel>
</AppBar>
</Page.BottomAppBar>
Next go to code behind page and write the below code to stream the video
var streamUri = new Uri(""); //replace your URL
var streamResponse = await AdaptiveMediaSource.CreateFromUriAsync(streamUri);
if (streamResponse.Status == AdaptiveMediaSourceCreationStatus.Success)
liveMedia.SetMediaStreamSource(streamResponse.MediaSource);
else
{
//not found
}
Before set the media source check the status property to verify that everything went correct
otherwise skip it.
By default it will start play the stream if you want to pause write the below code
private void pausBtn_Click(object sender, RoutedEventArgs e)
{
liveMedia.Pause();
}
You can play around the media control like the following function pause, play, mute, unmute
and volume increase etc.
Now Run the app and check the output look like the below video. Here I am going to stream
the live news channel.
In this part we are going to see how background file downloading workers in windows 10
UWP app.
Background transfer is used for long-term transfer or download operations such as video,
music, and images. For that time user will allow play around your app dont stop the user to
wait.
BackgroundDownloader class will help you to transfer or download the files from the server
event the app is running in foreground. If the user exits the app, the download will continue
in the background. You can check when the app is relaunched.
Lets see the steps how to download files from server.
Create new Windows 10 project and give a suitable name.
Design your xaml page. Here I will create one textbox to enter your download url then
textblock for showing the status and one button to start the download.XAML Code
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<TextBox x:Name="linkBox" Height="20" Width="200" Grid.Row="0"
HorizontalAlignment="Left"></TextBox>
<TextBlock x:Name="Statustext" Height="30" Grid.Row="1"
HorizontalAlignment="Center" TextWrapping="Wrap" Text="TextBlock"
VerticalAlignment="Top"/>
<Button x:Name="downloadBtn" Height="30" Grid.Row="2" Content="Download"
Click="downloadBtn_Click" HorizontalAlignment="Center" VerticalAlignment="Top"/>
</Grid>
Next we need to ensure that your app has the capability to access the internet. To enable the
capability follow the below steps
Double click your package.aapmainfest file in you solution explorer and enable the internet
client like below screen.
try
{
Statustext.Text = "Initializing...";
await downloadOperation.StartAsync().AsTask(cancellationToken.Token, progress);
}
catch (TaskCanceledException)
{
downloadOperation.ResultFile.DeleteAsync();
downloadOperation = null;
}
}
}
private void progressChanged(DownloadOperation downloadOperation)
{
int progress = (int)(100 * ((double)downloadOperation.Progress.BytesReceived /
(double)downloadOperation.Progress.TotalBytesToReceive));
Statustext.Text = String.Format("{0} of {1} kb. downloaded - %{2} complete.",
downloadOperation.Progress.BytesReceived / 1024,
downloadOperation.Progress.TotalBytesToReceive / 1024, progress);
switch (downloadOperation.Progress.Status)
{
case BackgroundTransferStatus.Running:
{
break;
}
case BackgroundTransferStatus.PausedByApplication:
{
break;
}
case BackgroundTransferStatus.PausedCostedNetwork:
{
break;
}
case BackgroundTransferStatus.PausedNoNetwork:
{
break;
}
case BackgroundTransferStatus.Error:
{
Statustext.Text = "An error occured while downloading.";
break;
}
}
if (progress >= 100)
{
downloadOperation = null;
}
}
private void downloadBtn_Click(object sender, RoutedEventArgs e)
{
Download();
}
}
In this part we are going to see the how to perform RSS Reader in Windows 10 application.
Create new Windows 10 project and give suitable name.
Now go to code behind and create new instance of SyndicationClient and SyndicationFeed
try
{
load(list, new Uri(value));
}
catch
{
}
list.Focus(FocusState.Keyboard);
}
}
}
Now run the application and enter your RSS feed Url in the given textbox.
Here I am going to feed my C# corner Articles
For Source Code
Output
Windows 10 SDK comes with lots of new sensors which helps the users to keep health fit to
know what the user needs. The new list of sensors are the following,
Altimeter
Activity Sensor
Barometer
Pedometer
Proximity Sensor
Lets see the sensor in detail.
To access the sensors API add the following namespace first,
using Windows.Devices.Sensors;
Altimeter
Altimeter helps to measure the relative altitude i.e. changes in elevation. The Altimeter has an
event called ReadingChanged and triggered whenever a new value is sensed by the Altimeter
sensor. ReportInterval property is used to set the time interval at which the sensor has to
report.Sample code
public void GetAltimeter()
{
Altimeter getAltiude = Altimeter.GetDefault();
AltimeterReading reading = getAltiude.GetCurrentReading();
getAltiude.ReportInterval = 100;
getAltiude.ReadingChanged += GetAltiude_ReadingChanged;
}
Activity Sensor
ActivitySensor will helps to detect the users activity based on the user motion context. These
sensor help to detect the motion of user either walking, running and idle etc. This sensor set to
idle state when the device is without any movement and also you can get the details up to
30days.
Sample code to get the activity reading
public async void GetActivity()
{
ActivitySensor activity =await ActivitySensor.GetDefaultAsync();
var reading = await activity.GetCurrentReadingAsync();
activity.ReadingChanged += new
TypedEventHandler<ActivitySensor,ActivitySensorReadingChangedEventArgs>(ReadingCh
anged);
Barometer
The Barometer is helps to measure the atmospheric pressure. The Barometer API has an Event
handler ReadingChanged which gets a new value is sensed by the sensor. The ReportInterval
property is used to set the interval at which the sensor has to report. GetCurrentReading method
is used to gets the current reading for the barometer.
Sample Code
public async void getBarometer()
{
Barometer barometerValues = Barometer.GetDefault();
BarometerReading reading = barometerValues.GetCurrentReading();
var getPressure = reading.StationPressureInHectopascals;
barometerValues.ReportInterval = 150;
barometerValues.ReadingChanged += Barometer_ReadingChanged;
}
private void Barometer_ReadingChanged(Barometer sender,
BarometerReadingChangedEventArgs args)
{
string values = args.Reading.ToString();
}
Pedometer
Pedometer helps you to count the users steps in walking and running and you can access
history details for up to 30 days.
Pedometer sensor comes with Windows Phone 10 and also in Microsoft Band.
Sample Code
public async void pedometer()
{
Pedometer readings = await Pedometer.GetDefaultAsync();
readings.ReportInterval = 100;
readings.ReadingChanged += Readings_ReadingChanged;
}
In this part we are going to see how to set different XAML page for specific device family.
The new Universal Windows Platform introduced a new feature DeviceFamily specific
views(UI) which allows developers to define specific XAML page for specific device
families (Desktop, Mobile.etc).
If we want to have different view for different device families. There are three ways to set
specific device family XAML view.
This method is the most common way to perform this task. Create a new folder in your
project, called DeviceFamily-Type. The type is the name of the device family type
(Mobile, Team, Desktop, IoT).
So in our sample I have created mobile specific view and it looks like the following screen
In our sample we will create a new folder called DeviceFamily-Mobile for specific view on
mobile device.
Let us take the MainPage.XAML in the project, with blue background we want this specific
XAML view for a mobile device family.
The next step would be adding a XAML view called the same as the page so in this case,
MainPage.xamlwill be added into the folder DeviceFamily-Mobile and looks like the
following,
This MainPage.XAML won't have any code-behind, it will use the code-behind of the main
MainPage.xaml.cs file.
Now run the app on a mobile device it will load the XAML from DeviceFamily-
Mobile/MainPage.xaml. For any other device family type, it will load the MainPage.xaml
from the main folder.
Change the grid background colour to green like below code
<Grid Background="Green">
</Grid>
Second one is DeviceFamily-Type in file name
The second method to perform the same thing is to create a new XAML View with, again,
the same name, but with DeviceFamily-Type extension in our MainPage, it would mean
adding a new XAML view file called MainPage.DeviceFamily-Mobile.xaml to the main
folder and looks like below screen.
Depending on the device family, one of the two XAML files will get loaded.
Now run the app in desktop and mobile and see the output looks like the following screen.
Mobile view
Desktop view
Part 22: Drawing and Inking Using New InkCanvas
Control for Windows 10 UWP App
In this part we will see how to capture user input and save it as image.
Windows 10 introduced built-in InkCanvas control to capture the user input. I am going to
show the use of InkCanvas control to capture the user touch input and save it as image.
In Windows 8.1 apps you had to create a Canvas, listen to input events, and render your own
strokes, but in Windows 10 use the built-in InkCanvas control to immediately capture use
input.
This control allows user to quickly enable inking for user and easily expand its functionality
by accessing the InkCanvass InkPresenter property. InkPresenter can be used to configure a
collection of user input through touch or mouse input.
Create a new windows 10 UWP app. Once successful created, go to MainPage.XAML page
and write the following code to design your page.
<InkCanvas x:Name="myCanvas" PointerPressed="myCanvas_PointerPressed"
PointerMoved="myCanvas_PointerMoved" PointerReleased="myCanvas_PointerReleased"
Margin="0,0,10,10"></InkCanvas>
The control looks like the following image.
Next got to code behind page and write the following code
First create new instance for InkPresenter.
InkPresenter myPresenter = myCanvas.InkPresenter;
Next define the input device type for Canvas control to let the control accepts inputs from
those devices.
Pen, Mouse and Touch.
myPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Pen
|Windows.UI.Core.CoreInputDeviceTypes.Mouse|Windows.UI.Core.CoreInputDeviceTypes.
Touch;
The whole code on canvas pointer pressed event looks like below
private void myCanvas_PointerPressed(object sender, PointerRoutedEventArgs e)
{
InkPresenter inkPresenter = myCanvas.InkPresenter;
inkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Pen
|Windows.UI.Core.CoreInputDeviceTypes.Mouse|Windows.UI.Core.CoreInputDeviceTypes.
Touch;
InkDrawingAttributes myAttributes = inkPresenter.CopyDefaultDrawingAttributes();
myAttributes.Color = Windows.UI.Colors.Crimson;
myAttributes.PenTip = PenTipShape.Circle;
myAttributes.PenTipTransform =
System.Numerics.Matrix3x2.CreateRotation((float)Math.PI / 4);
myAttributes.Size = new Size(2, 5);
inkPresenter.UpdateDefaultDrawingAttributes(myAttributes);
}
}
}
}
Now change the inkpresenter processing mode to erase to delete the ink
myCanvas.InkPresenter.InputProcessingConfiguration.Mode =
InkInputProcessingMode.Erasing;
If you are develop any security apps, sometimes we will need to disable to take screenshots
of your app. This feature was available in Windows 10 app.
You need to call the ViewManagement class ad get the current view screen.
Finally set the screen capture boo value to false like the following code.
Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().IsScreenCaptureEna
bled = false;