Hello world C++ Metro style app

Lire cet article en français 

C++/CX or WRL?

It is really easy to create a simple C++ app using C++/CX.

Microsoft is providing two supported ways to create Metro apps in C++, as explained in a previous post:

  • C++/CX language. C++ with MS specific language extensions like hat pointers.
  • A C++ template library (WRL). WRL is a C++ library-based solution, which offers template wrapper classes and explicit smart pointers.

But in fact, WRL is way too tedious and verbose to use. You not only have to manage COM interfaces, but also implement delegates and other WinRT stuff by hand. C++/CX is much simpler. This was just my opinion about WRL.

 

Create a C++ project

Of course you need Windows 8 installed on a touch enabled device with Visual Studio 11 Express.

In Visual Studio 11 express developer preview, click tap on menu File / New / Project, and choose Visual C++ Metro application:

Select OK to generate the sample project. MainPage.xaml file is automatically opened:

If you already know WPF, this should look familiar to you. It looks like a WPF project, but C# file is replaced by C++!

 

Create a few controls

MainPage.xaml is – as its name suggests – the Xaml language description of the main window. It is a UserControl.

For those familiar with Win32 resource files, Xaml can be seen as an improved of a resource language (string tables, DialogBox, menus, now it is in a Xaml file).

Visual Studio displays the XAML code form, along with the final rendering of the window. For now the window is empty.

Let’s add three controls in our main window: a label, an edit control, and an OK button. Insert the following text in file MainPage.xaml, inside tag <Grid> </ Grid>:

<StackPanel Orientation="Horizontal">
    <TextBlock Text="Enter 'hello, world':" Height="20" Margin="10"/>
    <TextBox Height="20" Margin="20" Width="200" x:Name="MyText"/>
    <Button Content="OK" Width="100" Height="20" Click="OnOK"/>
</StackPanel>

The Edit control (TextBox) has a MyText identifier that will be used in the code to retrieve the content.

The OK button is associated with an event handler OnOK which is still to be defined.

The three controls are encapsulated in a StackPanel control, which has the effect of aligning the three controls on a line.

 

Add C++ code

A Xaml file often comes with two other files: a .cpp and a .h file. Mainpage.xaml.cpp and Mainpage.xaml.h are linked to MainPage.xaml. Thus, C++ code for MainPage naturally find its place in these two files.

In Solution Explorer, click the small triangle in front MainPage.xaml to display the C++ associated files :

To define OnOK event handler, add the following code.

In Mainpage.xaml.h:

private:
    void OnOK(Platform::Object^ sender,
              Windows::UI::Xaml:RoutedEventArgs^ e);

In Mainpage.xaml.cpp:

void MainPage::OnOK(Platform::Object^ sender,
                    Windows::UI::Xaml::RoutedEventArgs^ e)
{
    String^ strInput = MyText->Text;
    String^ strMessage;
    if ( !wcsicmp( strInput->Data(), L"hello, world") )
        strMessage = L"Well done!";
    else strMessage = L"Try again";
    auto boxOK =
        ref new Windows::UI::Popups::MessageDialog(strMessage);
    boxOK->ShowAsync()->Start();
}

The code is fairly straightforward. The identifier MyText references the edit control. A MessageDialog displays a message depending on MyText content.

enter-hello-world

When the user presses OK, the MessageDialog is displayed.

Simple-metro-messagedialog

A Metro app is not supposed to exit. To close it anyway, use Visual Studio menu Debug/Stop debugging.

 

Customize MessageDialog

MessageDialog can be customized by adding buttons.

Each button in a MessageDialog is represented by a UICommand object, which combines a button caption and an event handler. The event handler method is called when the button is pushed.

UICommand^ btnYes = ref new UICommand(L"Yes I do",
    ref new UICommandInvokedHandler(this, &MainPage::OnYes));

Method MainPage::OnYes is called when the user pushes the button in the MessageDialog.

Here is the full MainPage.xaml.cpp code. A custom MessageDialog with two custom buttons is displayed:

using namespace Windows::UI::Popups;

void MainPage::OnOK(Platform::Object^ sender,
                    Windows::UI::Xaml::RoutedEventArgs^ e)
{
    String^ strInput = MyText->Text;
    if ( !wcsicmp( strInput->Data(), L"hello, world") )
    {
        // Create a simple default MessageDialog
        MessageDialog^ boxOK =
            ref new MessageDialog(ref new String(L"Well done!"));
        boxOK->ShowAsync()->Start(); // Display MessageDialog
    }
    else
    {
        // Create a MessageDialog with 2 buttons and 2 event handlers
        MessageDialog^ boxAsk =
            ref new MessageDialog("Do you want the solution?",
            L"You did not enter the magic phrase!");

        // Add buttons "Yes" and "No"
        UICommand^ btnYes = ref new UICommand(L"Yes I do",
            ref new UICommandInvokedHandler(this, &MainPage::OnYes));
        UICommand^ btnNo = ref new UICommand(L"No I don't",
            ref new UICommandInvokedHandler(this, &MainPage::OnNo));
        boxAsk->Commands->Append(btnYes);
        boxAsk->Commands->Append(btnNo);

        boxAsk->DefaultCommandIndex = 1; // Default btn index in Commands vector
        boxAsk->ShowAsync()->Start(); // Display MessageDialog
    }
}

void MainPage::OnYes(IUICommand^ command)
{
    // Give solution to user
    MyText->Text = L"hello, world";
}

void MainPage::OnNo(IUICommand^ command)
{
    MyText->Text = L"";
}

Custom-metro-MessageDialog

Source code project for C++/CX and for C# is available at http://code.msdn.microsoft.com/windowsapps/MessageDialog-sample-243ce23e

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>