Category Archives: C++ /CX

Using resumable functions in the CxxReadFileComponent sample

Hello,

Welcome back from holidays. A few weeks ago, I posted a note about updating the samples of my book to the November CTP of Visual C++. The main goal behind the update is to move away from using PPL tasks for WinRT asynchronous programming and instead use the new resumable functions available in the CTP.

Today is the beginning! The first sample I will talk about updating is the CxxReadFileComponent sample that discusses about building a C++ WinRT Component that can be consumed from other WinRT supported languages.

Before we begin:

  1. Get the updated sample here. We will use this sample as a starting point for our migration. Before we write actual code, it is important to note that the CTP is only supported along with Microsoft Visual Studio 2013.
  2. The CTP works with VS 2013. In case you do not have VS 2013, you can get either an express (free) edition or a trial edition here.
  3. In case you have not already downloaded the Visual C++ November CTP, please do so. You can download and install the CTP from this location.
  4. Install VS 2013 first and then the CTP.
  5. Time for action!!!

The first step is to migrate the solution from Microsoft Visual Studio 2012 to the 2013 version.

When you attempt to open the solution file in Visual Studio 2013, Visual Studio prompts you to retarget the solution for Windows 8.1 as shown in the dialog below. If you choose not to retarget, then you will have to install the Windows 8 development tools in order to build the solution.


For the purpose of this exercise, go ahead and retarget the solution to Windows 8.1 by first clicking on OK in the above dialog and then right click on the project in Solution Explorer and choose Retarget to Windows 8.1

Once you ask Visual Studio to retarget the solution to Windows 8.1, Visual Studio makes the necessary changes and opens the solution. Once the solution is fully loaded, right click on the CxxReadFileComponent project in Solution Explorer and choose Properties. In the Properties Dialog, under the Platform Toolset, choose Visual C++ Compiler Nov 2013 CTP (CTP_Nov2013) and click on OK.

The CxxReadFileComponent has one class named ReadFile. You can find the relevant code in the wrongly named files, Class1.h and Class1.cpp. The ReadFile class defines public methods that returns one of the IAsync* interfaces that all WinRT asynchronous methods are expected to return. This allows for consumption of such async operations from other languages. Before we go ahead with changing code, let’s open pch.h and add a new reference for a header. Add a new include reference for pplawait.h in pch.h which pulls in all the required declarations necessary for the new resumable functions.

Things to remember when using resumable functions in C++ for WinRT

  1. You cannot have resumable support for any WinRT method that returns one of the IAsync* interfaces.
  2. Only methods that return either a Task<T> or void can be resumable.

Making code changes

Now, it is time to make changes to code. Open Class1.cpp and navigate to the ReadBytes function. The original function is listed below:

Original ReadBytes function using PPL tasks:

You can see from the code above, using tasks and chaining them can become quite “messy”. With the new resumable functions, each task can be replaced with a single call to the underlying async API along with the __await keyword prepended to the API call. That’s it. No lambdas, no chaining etc.

Updated ReadBytes function using resumable functions:

task<UINT> ReadFile::ReadBytes(String^ fileName) __resumable

{

    StorageFolder^ item = KnownFolders::DocumentsLibrary;

    auto storageFile = __await item->GetFileAsync(fileName);

    auto istream = __await storageFile->OpenAsync(FileAccessMode::Read);

    auto reader = ref new DataReader(istream);

    return __await reader->LoadAsync(static_cast<UINT>(istream->Size));

}

Disclaimer: I have not added error handling. You can add proper if- checks and handle errors. The intention here is to show the ease of use of the resumable functions.

Changes made:

  1. All resumable methods have a __resumable identifier added at the end of the function declaration in both the header and the source files.
  2. Use the __await keyword when making calls to the WinRT Async APIs.
  3. That’s it!!

Similarly I made changes to the ReadBytesWithProgress function. The original function is listed below:

Original ReadBytesWithProgress function using PPL tasks:

Updated ReadBytesWithProgress function using resumable functions:

task<UINT> ReadFile::ReadBytesWithProgress(Platform::String^ fileName, Concurrency::progress_reporter<double> progress) __resumable

{

    StorageFolder^ item = KnownFolders::DocumentsLibrary;

    auto storageFile = __await item->GetFileAsync(fileName);

    progress.report(25.0);

    auto istream = __await storageFile->OpenAsync(FileAccessMode::Read);

    progress.report(50.0);

    auto reader = ref new DataReader(istream);

    progress.report(75.0);

    progress.report(100.0);

    return __await reader->LoadAsync(static_cast<UINT>(istream->Size));

}

With these changes made, build the solution and run the C# client test app. Make sure you have a text file named 127.txt in your Documents folder before you run the test app. Once you run the app, you can see that the app makes calls into your component and reads the number of bytes in the file using the updated methods, which really simplify writing asynchronous code using C++.

That’s it for today. See you soon for a next sample update. Stay tuned as this is getting very exciting!!

-Sridhar

How To: Use XAML and DirectX with C++ and create a compelling Windows Store app

One of the great benefits of using C++ to write Windows Store apps is the ability to mix and match various components and create compelling user experiences. There are a variety of apps that use XAML and DirectX together and have built delightful user experiences. For example, there is the FreshPaint app in the Windows Store that allows free form panting using touch or the OneNote app which allows for, as you know, note taking using a stylus (along with keyboard support).

However, if you want to take a look at code and learn from the experts and masters who have built such apps, there are very few options. One such code base is Project Austin which is a sample built by the C++ team to demonstrate using C++ (and CX) along with XAML and DirectX to build a great note taking app. Today’s post, however, is not about Project Austin. It is about a cool sample built by a colleague and C++ enthusiast, Thomas Petchel. Tom built a cool app named Weathr, which he describes as “3D weather app for Windows 8.1 using C++, DirectX, and XAML“. I cannot agree more. This is the best weather app I have seen in a long time and it shows in the user experience. Tom has also made the sources available for anyone to check out and play with. If you are serious about learning how to build such great experiences in your Windows Store apps, please check out the code. And if you make changes to the code, please ensure you contribute back the changes. This ensures that all the folks get the new stuff!!

I can talk about code and design, but I would leave that out for fellow programmers. The app is not on the Store though. So if you want to get the app, you have to build the sources J

Cheers and Happy Holidays!

-Sridhar

Coming Soon: Updated Code Samples with resumable support

Hello,

I will be posting a revised set of samples from my book, “Modern C++ and Windows Store apps” using the resumable function support available from the C++ November CTP. The impacted samples are the ones which use the WinRT Async APIs in conjunction with PPL tasks.

For more information on resumable functions, see this post on vcblog.

Stay tuned for the sample set.

-Sridhar

Learning C++ /CX with a console app on Windows 8.1

I have previously published a template on the VS Gallery that allows you to build console apps by writing C++ /CX code and not starting with XAML and code generation project default templates that VS ships. The previous blog entry is here and the link to the gallery item is here.

The good news is I have published a new template that allows you to use the Windows 8.1 SDK and winmd files to build command line apps while learning C++ /CX. You can get the template here.

Enjoy coding in C++ /CX!

-Sridhar

 

 

 

Targeting Modern C++ and Windows Store apps samples for Windows 8.1 – Part 1 of n

I have previously mentioned that I will not be updating “Modern C++ and Windows Store apps” to have an edition exclusively for Windows 8.1. My reason behind the decision is simple: The concepts and technologies I have introduced in the book continue to be relevant in Windows 8.1 and all of the samples will work on Windows 8.1. Having said that, during Windows 8.1 some WinRT APIs were deprecated and you will see warnings when you compile the samples for Windows 8.1. In this series of blog posts, I will show you how, with little effort and small changes, you can recompile the samples for Windows 8.1.

Note: This is just the first post in a series.

Let us begin with the very first example from the book, the DXBouncingBall sample. When you attempt to open the solution file in Visual Studio 2013, Visual Studio prompts you to retarget the solution for Windows 8.1 as shown in the dialog below. If you choose not to retarget, then you will have to install the Windows 8 development tools in order to build the solution.

For the purpose of this exercise, go ahead and retarget the solution to Windows 8.1 by first clicking on OK in the above dialog and then right click on the project in Solution Explorer and choose Retarget to Windows 8.1 as shown below.

Once you ask Visual Studio to retarget the solution to Windows 8.1, Visual Studio makes the necessary changes and opens the project. Once the project is fully loaded, try building the solution. You should see a series of warning messages indicating the usage of deprecated APIs. The warnings are all listed below.

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(35): warning C4973: ‘Windows::Graphics::Display::DisplayPropertiesEventHandler’ : marked as deprecated

1> Message: ‘The DisplayProperties type and related event handlers may be altered and or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1> This diagnostic occurred while importing type ‘Windows::Graphics::Display::DisplayPropertiesEventHandler ‘ from assembly ‘Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null’.

1> This diagnostic occurred while importing type ‘Windows::Graphics::Display::DisplayProperties ‘ from assembly ‘Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null’.

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(35): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::LogicalDpi::get’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(41): warning C4973: ‘Windows::Graphics::Display::DisplayPropertiesEventHandler’ : marked as deprecated

1> Message: ‘The DisplayProperties type and related event handlers may be altered and or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(41): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::LogicalDpiChanged::add’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(44): warning C4973: ‘Windows::Graphics::Display::DisplayPropertiesEventHandler’ : marked as deprecated

1> Message: ‘The DisplayProperties type and related event handlers may be altered and or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(44): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::OrientationChanged::add’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(47): warning C4973: ‘Windows::Graphics::Display::DisplayPropertiesEventHandler’ : marked as deprecated

1> Message: ‘The DisplayProperties type and related event handlers may be altered and or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(47): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::DisplayContentsInvalidated::add’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxpage.xaml.cpp(61): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::LogicalDpi::get’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxbase.cpp(177): warning C4973: ‘Windows::Graphics::Display::DisplayPropertiesEventHandler’ : marked as deprecated

1> Message: ‘The DisplayProperties type and related event handlers may be altered and or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1> This diagnostic occurred while importing type ‘Windows::Graphics::Display::DisplayPropertiesEventHandler ‘ from assembly ‘Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null’.

1> This diagnostic occurred while importing type ‘Windows::Graphics::Display::DisplayProperties ‘ from assembly ‘Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null’.

1>e:\projects\old\dxbouncingball\dxbouncingball\directxbase.cpp(177): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::LogicalDpi::get’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxbase.cpp(184): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::CurrentOrientation::get’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

1>e:\projects\old\dxbouncingball\dxbouncingball\directxbase.cpp(214): warning C4973: ‘Windows::Graphics::Display::DisplayProperties::CurrentOrientation::get’ : marked as deprecated

1> Message: ‘DisplayProperties may be altered or unavailable for releases after Windows 8.1. Instead, use DisplayInformation.’

Time for action! If you were to closely observe the warning messages, it should be pretty clear that there is one runtimeclass and some methods/properties/events associated with that particular class that are generating the warnings. That class happens to be the Windows::Graphics::Display::DisplayProperties. I will not go into the finer details of why this class has been deprecated in Windows 8.1 but for a teaser, it has to do with better multi-mon support J. Anyways back to our exercise.

The warning also informs us to use the newer class, DisplayInformation. This is one of the benefits of the great Intellisense support for WinRT apps in Visual Studio. All we need to do now, is replace the usage of DisplayProperties with DisplayInformation. Let’s begin the steps. I am showing you a table of the Windows 8 code and the new Windows 8.1 code to make the illustration easier. Each item in the table corresponds to the warnings in the order they appear.

 

File Name

Line Number in Windows 8 Code

Windows 8 Code

Windows 8.1 Code

DirectXPage.xaml.cpp

35

m_renderer->Initialize(

Window::Current->CoreWindow,

SwapChainPanel,

DisplayProperties::LogicalDpi

);

auto info = DisplayInformation::GetForCurrentView();

 

m_renderer->Initialize(


Window::Current->CoreWindow,

SwapChainPanel,

info->LogicalDpi

);

DirectXPage.xaml.cpp

41

DisplayProperties::LogicalDpiChanged +=


ref
new DisplayPropertiesEventHandler(this, &DirectXPage::OnLogicalDpiChanged);

info->DpiChanged +=


ref
new
TypedEventHandler<DisplayInformation^, Object^>( this, &DirectXPage::OnLogicalDpiChanged );

DirectXPage.xaml.cpp

44

DisplayProperties::OrientationChanged +=


ref
new DisplayPropertiesEventHandler(this, &DirectXPage::OnOrientationChanged);

info->OrientationChanged +=


ref
new
TypedEventHandler<DisplayInformation^, Object^>( this, &DirectXPage::OnOrientationChanged );

DirectXPage.xaml.cpp

47

DisplayProperties::DisplayContentsInvalidated +=


ref
new DisplayPropertiesEventHandler(this, &DirectXPage::OnDisplayContentsInvalidated);

info->DisplayContentsInvalidated +=


ref
new
TypedEventHandler<DisplayInformation^, Object^>( this, &DirectXPage::OnDisplayContentsInvalidated );

DirectXPage.xaml.cpp

61

m_renderer->SetDpi(DisplayProperties::LogicalDpi);

m_renderer->SetDpi( DisplayInformation::GetForCurrentView()->LogicalDpi );

DirectXBase.cpp

177

if (m_dpi != DisplayProperties::LogicalDpi)

{


return;

}

if ( m_dpi != DisplayInformation::GetForCurrentView()->LogicalDpi )

{


return;

}

DirectXBase.cpp

184

m_orientation != DisplayProperties::CurrentOrientation

m_orientation != DisplayInformation::GetForCurrentView()->CurrentOrientation

DirectXBase.cpp

214

m_orientation = DisplayProperties::CurrentOrientation

m_orientation = DisplayInformation::GetForCurrentView()->CurrentOrientation

DirectXPage.xaml.h

41-43

void OnLogicalDpiChanged(Platform::Object^ sender);

void OnOrientationChanged(Platform::Object^ sender);

void OnDisplayContentsInvalidated(Platform::Object^ sender);

void OnLogicalDpiChanged( Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args );

 

void OnOrientationChanged( Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args );

 

void OnDisplayContentsInvalidated( Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args );

 

Change the method signatures appropriately in the DirectXPage.xaml.cpp too and rebuild the solution. It should build clean with no warnings and your app should work on Windows 8.1 without any issues.

Try to resize the application window to different sizes and see how resizing and redrawing are all handled smoothly without having to explicitly write code. Is it not cool to write future proof code? J

 

Have fun!

-Sridhar

Will there be an update for “Modern C++ and Windows Store apps” for Windows 8.1?

With Windows 8.1 now released as a Consumer Preview enabling developers to try out and begin building apps for the new Operating System, I wanted to let folks know if there is an updated version of my book, “Modern C++ and Windows Store apps” under development.

When I began contemplating writing a book about Windows 8, I did not want to just show how to build Windows Store apps using C++ /CX and XAML. That would probably have been a great disservice to C++ developers since it would have restricted the scope of the book to just XAML. Don’t get me wrong. XAML is a great UX framework but I wanted to show how the power and flexibility of C++ and C++ /CX can be used to build a vide variety of apps that could be run both on the Desktop and Modern.

The more I thought about what to talk about in the book, the more my ideas began to crystallize around narrating the “C++ Renaissance” at Microsoft and in the industry. Discussing the “C++ Renaissance” is a vast topic in itself and I had to make a few hard decisions on the list of topics. After multiple deliberations, I ended up discussing the following topics:

  • Show the simplicity of developing Windows Store apps using C++ /CX
  • Important concepts of C++11
  • Introduction to C++ /CX
  • A High level tour of XAML
  • Using C++ /CX to combine XAML and DirectX
  • Advanced GPGPU Programming by using C++AMP in Desktop and Windows Store apps.
      • Under the covers of the Windows Runtime and the Windows Runtime Library (WRL)
      • Introducing the new native unit test support in VS2012.
      • Debugging tips for Windows Store apps
      • Performance tips for using XAML
      • Introduction to Windows Azure Mobile Services
      • A sneak preview of Windows Phone 8 “shared code”.

One of the ideas that I steadfastly took while developing samples and the narration was to focus explaining how C++ developers should be using XAML/DirectX interop techniques to make their apps stand apart from pure XAML or WWA counterparts. XAML/DirectX interop is really the “super pill” that can help C++ developers take full advantage of both the retained mode benefits of XAML and the immediate mode rendering provided by DirectX. When coupled with C++AMP, this has the added advantage of eking out maximum performance from the available hardware for all of your workloads.

With Windows 8.1, while XAML got a host of new controls, using those controls by itself is not an impossible task if you have already worked your way through my book. There simply is no point creating a new version of the book, when the fundamentals have already been discussed. All of the new updates are important but they are not breaking changes or stuff that is hard to incorporate. What is really interesting is the changes to the XAML/DirectX interop types. Does it warrant the creation of a new version of the book to explain 4 new interop types? I don’t think so. It, however, does merit explanation. So, going forward, I will begin posting content about the updated XAML/DirectX interop types. I will also update the samples from my book to show how to move code from Windows 8 to Windows 8.1. I hope that is of more value to readers instead of coming up with a new version of the book. What do you think? Please do let me know.

If you have noticed the topics I discussed in my book, attentive readers must have noticed that I did not discuss any communications or network API in the book. Is it a harbinger for things to come in future? Stay tuned for updates Smile

-Sridhar

What’s new in XAML for Windows 8.1?

//BUILD 2013 concluded last week and there was a ton of stuff to assimilate. I will attempt to summarize a few important changes for C++/XAML/DirectX developers in this blog post., focusing exclusively on the XAML/DirectX Interop scenarios.

If you are interested in knowing what is new with just the XAML framework (new controls, binding features etc), check out this great video from Tim Heuer.

New Stuff for XAML/DirectX interop scenarios using SwapChainPanel

1. A new SwapChainPanel control present in the Windows::UI::Xaml::Controls class.

2. In Windows 8, you were restricted to creating a full screen SwapChainBackgroundPanel and the swap chain had to be present at the root of your control hierarchy. The new SwapChainPanel controls removes these restrictions.

3. This does not mean you can have hundreds of SwapChainPanel controls in your app (Well, not even in the low double digits). Turns out using too many SwapChainPanel controls incurs a heavy cost. So restrict them to at the most 3 or 4. Do not go beyond that.

4. It is composable like any normal XAML element. You can have text layered below or above the control and have the XAML framework render content.

5. A Size Changed notification event provides for crisp re-drawing of content.

New Stuff for XAML/DirectX interop scenarios using the new SiS/VSiS

1. Has updated methods for faster D2D drawing by using drawing with a Direct2D DeviceContext.

2. Using the D2D DeviceContext allows the framework to batch the drawing requests.

3. Supports multi-threaded drawing.

4. Has new methods, SuspendDraw and ResumeDraw to enable you to suspend drawing operations and resume them later.

5. No longer needed to call BeginDraw on the XAML UI thread. In fact, BeginDraw, SuspendDraw and ResumeDraw can be called from any thread.

6. EndDraw should still be called on the UI thread. This allows the XAML framework to update the scene.

SwapChainPanel with Independent Input

1. The new SwapChainPanel now has support for processing touch, pen and mouse input on a background thread. This provides a path for low latency interactivity and high performance.

These are some of the high level changes. I encourage all of you to check out the excellent //BUILD 2013 talk by Bede Jordan,  a Senior Development Lead on the XAML team.

Enjoy the new C++/XAML/DirectX interop stuff in Windows 8.1

-Sridhar

A getting started template for creating XAML/DX apps using C++ and the SwapChainBackgroundPanel

This post comes courtesy of Wayne Ransier.

Start a XAML/C++ project in Visual Studio 2012 with the default Blank Template and replace the generated <Grid> element with a <SwapChainBackgroundPanel>

<SwapChainBackgroundPanel x:Name="DXSwapChainPanel">
</SwapChainBackgroundPanel>
If you build the solution now, the code compiles but the app crashes at runtime. The fix for the crash is simple.
Replace the OnLaunched method of your App class with the below code
void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args)
{
    m_mainPage = ref new MainPage();    
    Window::Current->Content = m_mainPage;
    Window::Current->Activate();
}

 

The code to replace the OnLaunched method of the App class is missing from the step by step application tutorial of the DrawIt application.

You can get the complete details about why the crash happens here.
A simple project template with this fix applied can be found here.
Copy this project template (the zip file) to “C:\Users\<username>\Documents\Visual Studio 2012\Templates\ProjectTemplates” and re-start Visual Studio 2012.
A new template with the name SCBPCppProject will be listed when you select Visual C++ project type in Visual Studio 2012.
Another nifty tip to keep in mind and this is obtained from the DrawIt sample from “Modern C++ and Windows Store apps” book.
There are a few styles that I have created for the ApplicationBar and placed them in Styles.xaml. In the sample I do not use the default generated styles from StandardStyles.xaml.
You can see the change in app.xaml for the DrawIt project.
<ResourceDictionary.MergedDictionaries>

    <!-- 
        Styles that define common aspects of the platform look and feel
        Required by Visual Studio project and item templates
     -->
    <ResourceDictionary Source="Styles.xaml"/>
</ResourceDictionary.MergedDictionaries>

 

Merging only the resources your application requires, into the Resource Dictionary is a nifty optimization.
A version of the sample that supports multi-touch can be downloaded here.
-Sridhar

Tip of the day: Using Constants in WinRT

This tip comes courtesy of a question asked on an internal discussion list. Deon from the C++ team provided the answer.

WinRT does not support constants. This means you cannot have code such as the following in C++ /CX:

public ref class FooClass sealed

{

public:

const int FooValue = 42;

}

How does one mimic constants with C++ /CX? Turns out using a static property is the solution.

namespace Foo

{

    public ref class FooClass sealed

    {

    public:

        static property int Value

        {

            int get()

            {

                return x;

            }

            void set(int _value)

            {

                x = _value;

            }

        }

    private:

        static int x;

    };

}

Having static properties allows you to write code as follows:

Foo::FooClass::Value = 42;

int i = Foo::FooClass::Value; 

Better, this code now works if you want to access such properties from other WinRT supported languages such as JS, C# etc.

Enjoy!

-Sridhar

Multi-touch drawing in Windows Store apps using C++ and DirectX

Windows 8 introduces input via multiple touch points. In the DrawIt sample of my book “Modern C++ and Windows Store apps”, I show how to add free form drawing on a XAML SwapChainBackgroundPanel using either touch, mouse or pen inputs. The sample restricted input to a single pointer i.e. you could draw using a finger or with left mouse button down or with a stylus if your device supported one. In today’s post, I will show how to move from a single pointer to supporting multiple pointers (restricted only by the number of touch points supported by the underlying hardware).

The DrawIt sample has two main classes: MainPage and ShapeRenderer. All of the changes I am about to make below are in the ShapeRenderer class.

  • The only change to MainPage is to add support for the PointerEntered event which in turn calls the corresponding method from ShapeRenderer.
  • I will also add an overlay to the code to show Pointer touch point properties like PointerId, the point where the touch occurs etc. These changes are also in ShapeRenderer
  • In the sample I enclose below, I have removed support for erasing. You are free to add it back as an exercise.

Handling Multiple Pointers

 

  1. Open the ShapeRenderer header file. Add a private member variable of type Platform::Collections::Map.

    Platform::Collections::Map<UINT, Windows::UI::Xaml::Input::Pointer^>^ m_PointerContact;

  2. Add another private variable of type UINT.

    UINT m_activeContacts;

  3. These two variables will be used to keep track of the multiple pointers that can be used to draw on screen.
  4. Add a function declaration for OnPointerEntered in the ShapeRenderer class. The ShapeRenderer class already has methods for OnPointerPressed, OnPointerReleased etc.

    void OnPointerEntered(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args);

  5. In the ShapeRenderer constructor, initialize the map as follows:

    m_PointerContact = ref new Map<UINT, Pointer^>();

  6. In the implementation for OnPointerEntered method, we will use the following logic. If the pointer that fires the “Entered” event exists in our map, we do nothing. Else we store the new pointer details in the map, increment the number of active pointer count and begin drawing.
  7. Next we call the Render method of the SwapChain.
  8. Similarly in the OnPointerPressed event handler, we check if the pointer exists in our saved collection. If yes, do nothing. Else proceed to drawing.
  9. In the OnPointerReleased event handler, call EndStroke of the InkManager and then Render the strokes.
  10. After the Render call, remove the released pointer details from the collection and decrement the active pointer count.
  11. That is all there is to handling multiple pointers.

Creating an overlay while drawing

 

  1. Add three new methods to the ShapeRenderer header file.

    void UpdateInfoPop(Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e);

    void DestroyInfoPop(Windows::UI::Xaml::Input::Pointer^ ptr);

    void CreateInfoPop(Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e);

  2. The logic to create the popup is simple. In the CreateInfoPop method, we create a TextBlock. Get the current touch point details and add the pointer details to the TextBlock. Apply a RenderTransform on the TextBlock by creating a TranslateTransform and offset the TextBlock position by 20 pixels from the point where the pointer is on screen. This allows the TextBlock to be visible and display contents.
  3. The UpdateInfoPop is used to move the TextBlock as the pointer moves on the screen. Check for all children of the SwapChain that matches the TextBlock control type and then use the name property to zero on the right pointer. Once the right pointer is identified, update the TextBlock position to the new position as determined by the pointer point.

That is all there is to adding information overlay to a pointer move event. The sample code is attached. Download the code and let me know your thoughts!

-Sridhar