By Paul Ferrill
Download Developing Desktop Apps for Ultrabook™ Devices in Windows* 8: Adapting Existing Apps [PDF 752KB]
Microsoft introduced the Extensible Application Markup Language (XAML) in conjunction with the release of version 3.0 of the Microsoft .NET Framework. XAML represents a totally different way of creating applications and was architected to support both traditional desktop applications and web-based apps using Microsoft Silverlight*. XAML is a significant departure from the Windows Forms approach in that it uses a more declarative approach to creating user interfaces (UIs).
Support for building XAML-based applications was somewhat limited in the beginning and required a more web design mentality, as much of the syntax was similar to building web applications using HTML. Microsoft Visual Studio* 2012 provides a rich set of design-time tools that makes this process much easier and is essentially on par with what you would expect if you’ve been developing Windows* desktop apps for any length of time.
The big news here is that existing XAML-based applications lend themselves well to adaptation for the new functionality found in the Ultrabook platform. This article looks at how you can quickly and easily add touch functionality to any XAML app with a minimal amount of code. We’ll start with a simple existing app and get it running on the Windows 8 desktop. Then, we’ll walk through the steps for adding new features to take advantage of what the Ultrabook has to offer.
Step 1: Compile and Run
Part 1 of this series looked at the steps required to convert projects from older versions of Visual Studio and get them to run with Visual Studio 2012. This step is only necessary if you have any references to libraries or DLLs that may not convert over properly. Examples include third-party libraries compiled for a specific operating system or version of the Microsoft .NET Framework.
Step 2: Evaluate the UI for Adaptation
Whether you’re building from scratch or adapting an application for touch, you need to consider a few design principles that Microsoft has outlined in Windows Touch Guide (see "For More Informationn" for a link). Basically, you need to think about the size and placement of any object you want a user to touch. Think about the application from the perspective of a touch-enabled device to look for ways to add new functionality.
Some user interactions typically accomplished with a right mouse click could just as easily be done using touch. Other candidate changes include using gestures to close or advance through a list of items. All of these tasks should be evaluated in the context of your specific application. XAML provides direct support for many of these types of interactions with little code. If your app is not XAML based, you’ll have to look at alternative methods that may require significantly more lines of code.
Step 3: Add Sensor Interaction to Enhance the Experience
One way to improve the look of an application is to change the color scheme based on available lighting. In part 1 of this series, you created a simple application to display the value from the ambient light sensor. Adapting this app for use in a production environment requires a few more lines of code to allow functions such as averaging the value over a period of time to keep from making adjustments too quickly. In Microsoft Visual Basic* .NET, this is easy to do using a timer control. Listing 1 shows the original code from part 1 modified to add a timer and average the value over 10 seconds.
Listing 1. Source code for a Visual Basic program to average the light sensor value over time
Imports Windows.Devices.Sensors Public Class Form1 Public avgvalue As Integer = 0 Public counter As Integer = 0 Public Sub New() ' This call is required by the designer. InitializeComponent() Timer1.Interval = 1000 Timer1.Enabled = False End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click If Timer1.Enabled = True Then Button1.Text = "Enable Timer" Timer1.Enabled = False Else Button1.Text = "Disable Timer" Timer1.Enabled = True End If End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick Dim mylight As LightSensor mylight = LightSensor.GetDefault Dim lightlevel As LightSensorReading = mylight.GetCurrentReading() counter += 1 If lightlevel IsNot Nothing Then avgvalue += lightlevel.IlluminanceInLux End If If counter Mod 10 = 0 Then TextBox1.Text = (avgvalue / 10).ToString avgvalue = 0 End If End Sub End Class
The first step is to initialize the timer in
Sub New() to fire once per second. You must set the timer interval to the number of milliseconds between events—hence the value
1000. In the
Timer1_Tick routine, you use a counter to average over 10 ticks, or 10 seconds. There’s no magic in the value of 10 seconds, and you might want to change the interval depending on your application. In the case of this demo program, you start with the timer disabled until the user clicks a button. When the button is clicked, the label is changed to Disable Timer, and the timer is enabled.
When the timer fires, you get the current sensor light level and add it to the
avgvalue variable. If you’ve reached 10 ticks, you divide
avgvalue by 10 and load the result into
TextBox1. Resetting the value for the avgvalue variable ensures that you get a new average each time. This demonstrates one simple way to add a sensor interaction to any application.
In part 1 of this series, you went through the steps to create a new project named
tstproj that required a manual editing step of the XML-based project file. In a nutshell, you simply create a new Visual Basic Windows Forms project, save it, and then exit Visual Studio 2012. Next, you need to use Microsoft Notepad to edit one of the files that Visual Studio created. With Notepad, you must add the following three lines to the
tstproj.vbproj file to have access to the sensor information:
<PropertyGroup> <TargetPlatformVersion>8.0</TargetPlatformVersion> </PropertyGroup>
Save these changes and exit Notepad. Launch Visual Studio 2012 and open the
tstproj project. With the changes to the
tstproj.vbproj file, you should be able to add a reference to the Core Windows application programming interface (API) functions by clicking Project > Add Reference, expanding the Windows in the navigation pane, and then selecting the Windows check box. The heading of this section should have the text "Targeting: Windows 8.0."
Step 4: Add New Features That Take Advantage of the Platform
Having a touch screen on a full-featured Ultrabook brings a whole new world of possibilities to applications. This next sample shows how an existing XAML-based application can use touch with a minimal amount of coding. The basic application fully supports multifinger touch functions, including pan, zoom, and rotation. You can zoom in or out using your thumb and forefinger or one finger and both hands. Figure 1 shows what the app looks like.
Figure 1.Example of an XAML touch application
The application has a single canvas with an image loaded (
Common_Jezebel_Delias.jpg). From there, you set the
IsManipulationEnabled property to True along with references to the code that will handle the actual manipulation.
Listing 2 shows the XAML code.
Listing 2. XAML code for the image rotation by touch example
<Window x:Class="Manipulations.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Rotate and Zoom" WindowState="Maximized" Height="600" Width="800"> <Canvas x:Name="_canvas" ManipulationStarting="_canvas_ManipulationStarting" ManipulationDelta="_canvas_ManipulationDelta" > <Image IsManipulationEnabled="True" Width="200" Source="Common_Jezebel_Delias.jpg"> <Image.RenderTransform> <MatrixTransform Matrix="1 0 0 1 200 200" /> </Image.RenderTransform> </Image> </Canvas> </Window>
The Visual Basic code behind the XAML is not complicated at all. Listing 3 shows what it looks like.
Listing 3. Visual Basic code behind the image rotation by touch example
Namespace Manipulations ''' <summary> ''' Interaction logic for MainWindow.xaml ''' </summary> Partial Public Class MainWindow Inherits Window Public Sub New() InitializeComponent() End Sub Private Sub _canvas_ManipulationStarting(sender As Object, _ e As ManipulationStartingEventArgs) e.ManipulationContainer = _canvas e.Handled = True End Sub Private Sub _canvas_ManipulationDelta(sender As Object, _ e As ManipulationDeltaEventArgs) Dim element = TryCast(e.OriginalSource, UIElement) Dim transform = TryCast(element.RenderTransform, MatrixTransform) Dim matrix__1 = If(transform Is Nothing, Matrix.Identity, transform.Matrix) matrix__1.ScaleAt(e.DeltaManipulation.Scale.X, e.DeltaManipulation.Scale.Y, _ e.ManipulationOrigin.X, e.ManipulationOrigin.Y) matrix__1.RotateAt(e.DeltaManipulation.Rotation, e.ManipulationOrigin.X, _ e.ManipulationOrigin.Y) matrix__1.Translate(e.DeltaManipulation.Translation.X, _ e.DeltaManipulation.Translation.Y) element.RenderTransform = New MatrixTransform(matrix__1) e.Handled = True End Sub End Class End Namespace
Microsoft makes several sample applications available that demonstrate the manipulation piece. It’s basically a matrix transformation using the inherent capabilities of the platform. The two subroutines
ManipulationDelta are declared in the XAML and serviced in the Visual Basic code.
Step 5: Make an Example Graphing App Touch Capable
The final example adds touch functionality to an existing XAML-based graphing app. The basic starting point is an app that displays sales information by region in a pie chart. Figure 2 shows what the initial app looks like.
Figure 2.Example pie chart application
One place you can add functionality is in the event handlers of the XAML object. To get to them, simply click the Lightning Bolt icon in the Properties dialog box (see Figure 3). Many events are available to code against should you so choose.
Figure 3.Event handlers for the XAML chart object
Entering text in any of these boxes creates a stub event handler to which you can add any code you like. In Figure 3, you can see the two names TouchDown and TouchMove entered next to their respective events. These events are distinct from mouse events, although they do follow some of the same processing steps.
Inside your processing code, you have access to a wide range of methods and properties associated with the
pieChart. Microsoft IntelliSense* is a great way to explore what’s available if you’re not familiar with the entire list. Figure 4 shows an example of what you should see after typing
pieChart followed by a period.
Figure 4.IntelliSense for methods and properties of the XAML chart object
If you’re unfamiliar with how a particular object behaves at runtime, you can use a trick to set a breakpoint in your code, and then use the Locals dialog box in Visual Studio 2012 to see the names and values of the various properties. To demonstrate this technique, create a
TouchDown event handler, and then add a
Debug.Writeline statement to give you a place to set a breakpoint. Figure 5 shows what that looks like.
Figure 5.Locals dialog box from Visual Studio 2012
All of these variables are available to the code behind the XAML page and in event-handling routines such as TouchDown. It’s up to you to decide the kind of functionality to add to your application to give it that extra bit of pizzazz. Some possibilities include a pop-up window in which to view the underlying data or even change it. You could also add the ability to save the image to a file. Both of these options are relatively simple to implement.
If you have an existing XAML-based application, you’re way ahead of the curve in moving to the desktop in Windows 8. If your application is Windows Forms based, you still have access to the sensor data, as shown in the light level sample. Basic touch functions will work just like mouse clicks for things like list boxes or to scroll through a grid. Adding multitouch features is much simpler with XAML apps, so if you need that, you’ll want to consider moving to a XAML-based design.
The key thing to take away from these articles is how easy it is to add functionality to your application to take advantage of the new Ultrabook capabilities. It really doesn’t take that much code to get full multitouch functionality, as shown in the picture sample. Take the time to read through the Microsoft documentation and become familiar with the new API functions. Understanding how to add the code and what you need to implement your new features will make the process much easier.
For More Information
- Windows Touch Guide at http://archive.msdn.microsoft.com/wintouchguide
- MSDN Sensors Reference at http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.sensors.aspx
- Windows SDK for Windows 8 at http://msdn.microsoft.com/en-us/windows/hardware/hh852363.aspx
- Windows 8 API List at http://msdn.microsoft.com/en-us/library/windows/desktop/hh920511%28v=vs.85%29.aspx
- Windows 8 Touch Guidance at http://download.microsoft.com/download/8/A/6/8A652B51-AF09-4A5A-888C-A0465D00FE5E/Windows%208%20Touch%20Guidance.pdf
Intel, the Intel logo, and Ultrabook are trademarks of Intel Corporation in the US and/or other countries.
Copyright © 2013 Intel Corporation. All rights reserved.
*Other names and brands may be claimed as the property of others.