Category Archives: C++ /CX

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

It’s time to move away from Turbo C++

You might be surprised to hear that a good number of colleges (at least in India) still rely on using the ages old Turbo C++ package to teach aspiring students C++. With a new language standard and great library support, it is now time to bid goodbye to Turbo C++. I answered a few questions about Turbo C++ and Modern C++ in this month’s edition of PCQuest (Thank you Hiren Mehta and other good folks from PCQuest). Attaching the Q&A below.

201306-PC Quest-Sridhar

 

While Visual Studio 2012 is a great tool for developing Windows apps using C++, there are also similar utilities for other platforms that support the C++11 standard. These include, but are not limited to, GCC, Clang etc. We owe it to aspiring students and should teach and train them on the latest language standard. In case you have not checked out Modern C++, I urge you all to check out the new language and you will be pleasantly surprised at the changes!!

 

-Sridhar

 

Modern C++ and Windows Store apps giveaway – An update

I wanted to provide a quick update on the winning responses so far to book contest I have announced a few weeks back. I am humbled by the responses I have received so far. The winning responses, from the mails I have received until now are:

I am excited to apply modern C++ to code snappy and responsive Windows 8 metro apps using asynchronous functions, now wonderfully described in Sridhar’s book on Windows 8 application programming. I’ve been trying to find the best sources of information for Windows 8 application programming to write apps that work on phone/tablet and PC.  I plan to write applications that are education games or tools related to biology.”

“Thanks for writing a book on using modern C++ with Windows 8. I am a long time C++ developer, having worked for many years with Symbian and Qt. This book has come at the right time for me to update my skills 🙂 The fascinating thing about Windows has always been its reach. No question about it. But with Windows 8, I feel that Microsoft is now at the forefront of design as well. I love the way the “modern” apps look and perform on my tablet, and I am amazed by their performance even on this old device. Modern C++ provides me with an easy pathway to the Windows 8 ecosystem. Ever since Microsoft released the source for Project Austin, I have been looking at the possibility of developing an application for Windows 8 with C++. With the release of your book, I hope to learn a few tricks which will make my task much easier.

“My name is XXXX and I work for a XYZ company and write software that processes large amounts of data and visualizes it using various plot types such as scatter, histogram, density, and contour plots. The software also controls the hardware during run-time data acquisition. Currently the software runs on the desktop using WPF and C#. As the data rates and file sizes increase I am starting to hit the threshold of the C# – .Net technology. I am now seriously considering writing the software in C++ 11 and Windows Store App. Previously I did some prototyping with C++/CLI and WPF, and the performance while better was not enough to justify the move. The boundary between C++ and C# forced some design compromises and to be honest had some performance problems. With WinRT C++/CX and native XAML the story becomes very intriguing. While there are still boundary problems to aware of (avoid ‘chatty’ api’s) I believe the design will be much cleaner and have much better performance. Additionally I have been working with C++ Amp to do a lot of parallel processing. The results have been very encouraging. It seems as though the stars have aligned in terms of performance (C++, and AMP), Fast and Fluid UI (Windows Store App), and my existing knowledge of Xaml and WPF. I believe this combination will give me the opportunity to write some great software that performs well, and looks great and runs on tablet and eventually mobile (reduced function set.)  I think that the combination will truly give me full power at my fingertips to extract the most from the hardware available. I am looking for the knowledge of how to best use Modern C++ with the new WinRT framework to quickly come come up to speed. ”

 

I still have 6 copies to giveaway. If you want a copy, please do let me know.

-Sridhar

Purchase Modern C++ and Windows Store apps in India

Hi,

Wanted to provide a quick update on the availability of my book, “Modern C++ and Windows Store apps”, in India.

Get the eBook in Adobe PDF: http://www.infibeam.com/eBooks/modern-c-windows-store-apps-sridhar-poduri-pdf-ebook-download/9780989020800-BEPDF.html

Get the paperback edition: http://www.junglee.com/Modern-C-Windows-Store-Apps/dp/0989020800/ref=sr_1_1?ie=UTF8&qid=1364203192&sr=8-1

Thanks,

Sridhar

[Updated with purchase and discount links] Modern C++ and Windows Store Apps – A book about Modern C++ and native technologies

Over the past few months, I have been writing a book on developing apps using C++ and the various native technologies shipping as part of the Windows 8 wave. Some of these technologies include: C++11, C++ /CX, native XAML, the Windows Runtime, C++AMP, Windows Azure Mobile Services etc. I am happy to announce that the Kindle version of “Modern C++ and Windows Store apps” will be available shortly for purchase via the Amazon website. A paperback edition will also be available soon.

For purchasing the paperback edition of the book, please visit this link. You can use the discount code 5C56GCKN to get 20% discount off MRP.

For folks interested in an electronic edition, you can purchase a Kindle edition on Amazon

A quick update: This is just me self-publishing the book thereby bringing the work to its logical conclusion.

For the benefit of everyone, I am listing some of the topics that await anyone who picks up a copy of this book. For the more adventurous amongst us who would rather prefer to play with code, the book samples can be downloaded from the Downloads section of this blog.

The new native API
What is a Windows 8 App?
Quick walkthrough of a Windows 8 App

Hello Modern C++
Move semantics
Welcome to the Component Extensions
The C++ /CX Type System
Asynchronous Programming in C++ /CX
Building a WinRT component using C++ /CX and ISO-C++
Guidance on the use of C++ /CX

Introduction to XAML
Hello World with XAML and C++ /CX
Basic XAML Syntax
Using Panels to Layout UX
Basic XAML Controls
Windows 8 Signature XAML Controls
Handling Events
Markup Extensions
Data Binding
Binding to a Data Model
Building a XAML custom control
Using Animations in XAML Controls

Introduction to XAML + DirectX
SurfaceImageSource
VirtualSurfaceImageSource
Design considerations when using SiS and VSiS
SwapChainBackgroundPanel
The DrawIt Application – C++, XAML and DirectX

The C++ AMP Library
The ImageEffects application

Playing by the rules of the Windows Runtime
Introduction to the Windows Runtime Library
Hello World XAML App using Windows Runtime Library

Getting Started with Windows Store apps and Windows Azure Mobile Services
Creating a simple Windows Store app with Windows Azure Mobile Services
Supporting Push Notifications using Windows Azure Mobile Services

And more….

I had a lot of fun writing this stuff and learning along the way. I hope there are concepts that you can apply to your work as you build apps for the Windows 8 Store using C++.

Please send feedback on the book contents directly to win8book at sridharpoduri dot com