Visual Studio Hello World



Our first app is a 'Hello, World!' App that demonstrates some basic features of interactivity, layout, and styles. Begin by creating a new project in Microsoft Visual Studio. Create a Blank App (C/WinRT) project, and name it HelloWorldCppWinRT. The first step involves the creation of a new project in Visual Studio. After launching Visual Studio.

-->

This topic describes how to write a very small Universal Windows driver using Kernel-Mode Driver Framework (KMDF) and then deploy and install your driver on a separate computer.

To get started, be sure you have Microsoft Visual Studio, the Windows SDK, and the Windows Driver Kit (WDK) installed.

Debugging Tools for Windows is included when you install the WDK.

Create and build a driver

  1. Open Microsoft Visual Studio. On the File menu, choose New > Project.

  2. In the New Project dialog box, in the left pane, go to Visual C++ > Windows Drivers > WDF.

  3. In the middle pane, select Kernel Mode Driver, Empty (KMDF).

  4. In the Name field, enter 'KmdfHelloWorld' for the project name.

    Note

    When you create a new KMDF or UMDF driver, you must select a driver name that has 32 characters or less. This length limit is defined in wdfglobals.h.

  5. In the Location field, enter the directory where you want to create the new project.

  6. Check Create directory for solution. Select OK.

    Visual Studio creates one project and a solution. You can see them in the Solution Explorer window, shown here. (If the Solution Explorer window is not visible, choose Solution Explorer from the View menu.) The solution has a driver project named KmdfHelloWorld.

  7. In the Solution Explorer window, select and hold (or right-click) the KmdfHelloWorld project and choose Properties. Navigate to Configuration Properties > Driver Settings > General, and note that Target Platform defaults to Universal. Select Apply, and then select OK.

  8. In the Solution Explorer window, again select and hold (or right-click) the KmdfHelloWorld project, choose Add, and then select New Item.

  9. In the Add New Item dialog box, select C++ File. For Name, enter 'Driver.c'.

    Select Add. The Driver.c file is added under Source Files, as shown here.

Write your first driver code

Now that you've created your empty Hello World project and added the Driver.c source file, you'll write the most basic code necessary for the driver to run by implementing two basic event callback functions.

  1. In Driver.c, start by including these headers:

    Tip

    If you can't add Ntddk.h, open Configuration -> C/C++ -> General -> Additional Include Directories and add C:Program Files (x86)Windows Kits10Include<build#>km, replacing <build#> with the appropriate directory in your WDK installation.

    Ntddk.h contains core Windows kernel definitions for all drivers, while Wdf.h contains definitions for drivers based on the Windows Driver Framework (WDF).

  2. Next, provide declarations for the two callbacks you'll use:

  3. Use the following code to write your DriverEntry:

    DriverEntry is the entry point for all drivers, like Main() is for many user mode applications. The job of DriverEntry is to initialize driver-wide structures and resources. In this example, you printed 'Hello World' for DriverEntry, configured the driver object to register your EvtDeviceAdd callback's entry point, then created the driver object and returned.

    The driver object acts as the parent object for all other framework objects you might create in your driver, which include device objects, I/O queues, timers, spinlocks, and more. For more information about framework objects, see Introduction to Framework Objects.

    Tip

    For DriverEntry, we strongly recommend keeping the name as 'DriverEntry' to help with code analysis and debugging.

  4. Next, use the following code to write your KmdfHelloWorldEvtDeviceAdd:

    EvtDeviceAdd is invoked by the system when it detects that your device has arrived. Its job is to initialize structures and resources for that device. In this example, you simply printed out a 'Hello World' message for EvtDeviceAdd, created the device object, and returned. In other drivers you write, you might create I/O queues for your hardware, set up a device context storage space for device-specific information, or perform other tasks needed to prepare your device.

    Tip

    For the device add callback, notice how you named it with your driver's name as a prefix (KmdfHelloWorldEvtDeviceAdd). Generally, we recommend naming your driver's functions in this way to differentiate them from other drivers' functions. DriverEntry is the only one you should name exactly that.

  5. Your complete Driver.c now looks like this:

  6. Save Driver.c.

This example illustrates a fundamental concept of drivers: they are a 'collection of callbacks' that, once initialized, sit and wait for the system to call them when it needs something. This could be a new device arrival event, an I/O request from a user mode application, a system power shutdown event, a request from another driver, or a surprise removal event when a user unplugs the device unexpectedly. Fortunately, to say 'Hello World,' you only needed to worry about driver and device creation.

Next, you'll build your driver.

Build the driver

  1. In the Solution Explorer window, select and hold (or right-click) Solution 'KmdfHelloWorld' (1 project) and choose Configuration Manager. Choose a configuration and platform for the driver project. For this exercise, we choose Debug and x64.

  2. In the Solution Explorer window, select and hold (or right-click) KmdfHelloWorld and choose Properties. In Wpp Tracing > All Options, set Run Wpp tracing to No. Select Apply and then OK.

  3. To build your driver, choose Build Solution from the Build menu. Visual Studio shows the build progress in the Output window. (If the Output window is not visible, choose Output from the View menu.) When you have verified that the solution built successfully, you can close Visual Studio.

  4. To see the built driver, in File Explorer, go to your KmdfHelloWorld folder, and then to C:KmdfHelloWorldx64DebugKmdfHelloWorld. The folder includes:

    • KmdfHelloWorld.sys -- the kernel-mode driver file
    • KmdfHelloWorld.inf -- an information file that Windows uses when you install the driver
    • KmdfHelloWorld.cat -- a catalog file that the installer uses to verify the driver's test signature

Tip

If you see DriverVer set to a date in the future when building your driver, change your driver project settings so that Inf2Cat sets /uselocaltime. To do so, use Configuration Properties->Inf2Cat->General->Use Local Time. Now both Stampinf and Inf2Cat use local time.

Deploy the driver

Typically when you test and debug a driver, the debugger and the driver run on separate computers. The computer that runs the debugger is called the host computer, and the computer that runs the driver is called the target computer. The target computer is also called the test computer.

So far you've used Visual Studio to build a driver on the host computer. Now you need to configure a target computer.

  1. Follow the instructions in Provision a computer for driver deployment and testing (WDK 10).

    Tip

    When you follow the steps to provision the target computer automatically using a network cable, take note of the port and key. You'll use them later in the debugging step. In this example, we'll use 50000 as the port and 1.2.3.4 as the key.

    In real driver debugging scenarios, we recommend using a KDNET-generated key. For more information about how to use KDNET to generate a random key, see the Debug Drivers - Step by Step Lab (Sysvad Kernel Mode) topic.

  2. On the host computer, open your solution in Visual Studio. You can double-click the solution file, KmdfHelloWorld.sln, in your KmdfHelloWorld folder.

  3. In the Solution Explorer window, select and hold (or right-click) the KmdfHelloWorld project, and choose Properties.

  4. In the KmdfHelloWorld Property Pages window, go to Configuration Properties > Driver Install > Deployment, as shown here.

  5. Check Remove previous driver versions before deployment.

  6. For Target Device Name, select the name of the computer that you configured for testing and debugging. In this exercise, we use a computer named MyTestComputer.

  7. Select Hardware ID Driver Update, and enter the hardware ID for your driver. For this exercise, the hardware ID is RootKmdfHelloWorld. Select OK.

    Note

    In this exercise, the hardware ID does not identify a real piece of hardware. It identifies an imaginary device that will be given a place in the device tree as a child of the root node. For real hardware, do not select Hardware ID Driver Update; instead, select Install and Verify. You'll see the hardware ID in your driver's information (INF) file. In the Solution Explorer window, go to KmdfHelloWorld > Driver Files, and double-click KmdfHelloWorld.inf. The hardware ID is located under [Standard.NT$ARCH$].

  8. On the Build menu, choose Deploy Solution. Visual Studio automatically copies the files required to install and run the driver to the target computer. This may take a minute or two.

    When you deploy a driver, the driver files are copied to the %Systemdrive%drivertestdrivers folder on the test computer. If something goes wrong during deployment, you can check to see if the files are copied to the test computer. Verify that the .inf, .cat, test cert, and .sys files, and any other necessary files, are present in the %systemdrive%drivertestdrivers folder.

    For more information about deploying drivers, see Deploying a Driver to a Test Computer.

Install the driver

With your Hello World driver deployed to the target computer, now you'll install the driver. When you previously provisioned the target computer with Visual Studio using the automatic option, Visual Studio set up the target computer to run test signed drivers as part of the provisioning process. Now you just need to install the driver using the DevCon tool.

  1. On the host computer, navigate to the Tools folder in your WDK installation and locate the DevCon tool. For example, look in the following folder:

    C:Program Files (x86)Windows Kits10Toolsx64devcon.exe

    Copy the DevCon tool to your remote computer.

  2. On the target computer, install the driver by navigating to the folder containing the driver files, then running the DevCon tool.

    1. Here's the general syntax for the devcon tool that you will use to install the driver:

      devcon install <INF file> <hardware ID>

      The INF file required for installing this driver is KmdfHelloWorld.inf. The INF file contains the hardware ID for installing the driver binary, KmdfHelloWorld.sys. Recall that the hardware ID, located in the INF file, is RootKmdfHelloWorld.

    2. Open a Command Prompt window as Administrator. Navigate to your folder containing the built driver .sys file and enter this command:

      devcon install kmdfhelloworld.inf rootkmdfhelloworld

      If you get an error message about devcon not being recognized, try adding the path to the devcon tool. For example, if you copied it to a folder on the target computer called C:Tools, then try using the following command:

      c:toolsdevcon install kmdfhelloworld.inf rootkmdfhelloworld

      A dialog box will appear indicating that the test driver is an unsigned driver. Select Install this driver anyway to proceed.

Debug the driver

Now that you have installed your KmdfHelloWorld driver on the target computer, you'll attach a debugger remotely from the host computer.

  1. On the host computer, open a Command Prompt window as Administrator. Change to the WinDbg.exe directory. We will use the x64version of WinDbg.exe from the Windows Driver Kit (WDK) that was installed as part of the Windows kit installation. Here is the default path to WinDbg.exe:

    C:Program Files (x86)Windows Kits10Debuggersx64

  2. Launch WinDbg to connect to a kernel debug session on the target computer by using the following command. The value for the port and key should be the same as what you used to provision the target computer. We'll use 50000 for the port and 1.2.3.4 for the key, the values we used during the deploy step. The k flag indicates that this is a kernel debug session.

    WinDbg -k net:port=50000,key=1.2.3.4

  3. On the Debug menu, choose Break. The debugger on the host computer will break into the target computer. In the Debugger Command window, you can see the kernel debugging command prompt: kd>.

  4. At this point, you can experiment with the debugger by entering commands at the kd> prompt. For example, you could try these commands:

  5. To let the target computer run again, choose Go from the Debug menu or press 'g,' then press 'enter.' Maamadurai movie.

  6. To stop the debugging session, choose Detach Debuggee from the Debug menu.

    Important

    Make sure you use the 'go' command to let the target computer run again before exiting the debugger, or the target computer will remain unresponsive to your mouse and keyboard input because it is still talking to the debugger.

For a detailed step-by-step walkthrough of the driver debugging process, see Debug Universal Drivers - Step by Step Lab (Echo Kernel-Mode).

For more information about remote debugging, see Remote Debugging Using WinDbg.

Related topics

-->

This topic walks you through creating a Windows 10 Universal Windows Platform (UWP) 'Hello, World!' app using C++/WinRT. The app's user interface (UI) is defined using Extensible Application Markup Language (XAML).

C++/WinRT is an entirely standard modern C++17 language projection for Windows Runtime (WinRT) APIs. For more info, and more walkthroughs and code examples, see the C++/WinRT documentation. A good topic to begin with is Get started with C++/WinRT.

Set up Visual Studio for C++/WinRT

For info about setting up Visual Studio for C++/WinRT development—including installing and using the C++/WinRT Visual Studio Extension (VSIX) and the NuGet package (which together provide project template and build support)—see Visual Studio support for C++/WinRT.

To download Visual Studio, see Downloads.

For an introduction to XAML, see XAML overview

Create a Blank App (HelloWorldCppWinRT)

Our first app is a 'Hello, World!' app that demonstrates some basic features of interactivity, layout, and styles.

Begin by creating a new project in Microsoft Visual Studio. Create a Blank App (C++/WinRT) project, and name it HelloWorldCppWinRT. Make sure that Place solution and project in the same directory is unchecked. Target the latest generally-available (that is, not preview) version of the Windows SDK.

In a later section of this topic, you'll be directed to build your project (but don't build until then).

About the project files

Typically, in the project folder, each .xaml (XAML markup) file has a corresponding .idl, .h, and .cpp file. Together, those files compile into a XAML page type.

You can modify a XAML markup file to create UI elements, and you can bind those elements to data sources (a task known as data binding). You modify the .h, and .cpp files (and sometimes the .idl file) to add custom logic for your XAML page—event handlers, for example.

Let's look at some of the project files.

  • App.idl, App.xaml, App.h, and App.cpp. These files represent your app's specialization of the Windows::UI::Xaml::Application class, which includes your app's entry point. App.xaml doesn't contain any page-specific markup, but you can add user interface element styles there, as well as any other elements that you want to be accessible from all pages. The .h and .cpp files contain handlers for various application lifecycle events. Typically, you add custom code there to initialize your app when it starts, and to perform cleanup when it's either suspended or terminated.
  • MainPage.idl, MainPage.xaml, MainPage.h, and MainPage.cpp. Contain the XAML markup, and implementation, for the default main (startup) page type in an app, which is the MainPage runtime class. MainPage has no navigation support, but it provides some default UI, and an event handler, to get you started.
  • pch.h and pch.cpp. These files represent your project's precompiled header file. In pch.h, include any header files that don't change often, and then include pch.h in other files in the project.

A first look at the code

Runtime classes

As you may know, all of the classes in a Universal Windows Platform (UWP) app written in C# are Windows Runtime types. But when you author a type in a C++/WinRT application, you can choose whether that type is a Windows Runtime type, or a regular C++ class/struct/enumeration.

Any XAML page type in your project needs to be a Windows Runtime type. So MainPage is a Windows Runtime type. Specifically, it's a runtime class. Any type that's consumed by a XAML page also needs to be a Windows Runtime type. When you're writing a Windows Runtime component, and you want to author a type that can be consumed from another app, then you'll author a Windows Runtime type. In other cases, your type can be a regular C++ type. Generally speaking, a Windows Runtime type can be consumed using any Windows Runtime language.

One good indication that a type is a Windows Runtime type is that it's defined in Microsoft Interface Definition Language (MIDL) inside an Interface Definition Language (.idl) file. Let's take MainPage as an example.

And here's the basic structure of the implementation of the MainPage runtime class, and its activation factory, as seen in MainPage.h.

For more details about whether or not you should author a runtime class for a given type, see the topic Author APIs with C++/WinRT. And for more info about the connection between runtime classes and IDL (.idl files), you can read and follow along with the topic XAML controls; bind to a C++/WinRT property. That topic walks through the process of authoring a new runtime class, the first step of which is to add a new Midl File (.idl) item to the project.

Now let's add some functionality to the HelloWorldCppWinRT project.

Step 1. Modify your startup page

In Solution Explorer, open MainPage.xaml so that you can author the controls that form the user interface (UI).

Delete the StackPanel that's in there already, as well as its contents. In its place, paste the following XAML.

This new StackPanel has a TextBlock that prompts for the user's name, a TextBox that accepts the user's name, a Button, and another TextBlock element.

Hello

Since we deleted the Button named myButton, we'll have to remove the reference to it from the code. So, in MainPage.cpp, delete the line of code inside the MainPage::ClickHandler function.

At this point, you've created a very basic Universal Windows app. To see what the UWP app looks like, build and run the app.

In the app, you can type into the text box. But clicking the button doesn't do anything yet.

Step 2. Add an event handler

Visual Studio Hello World Java

In MainPage.xaml, find the Button named inputButton, and declare an event handler for its ButtonBase::Click event. The markup for the Button should now look like this.

Implement the event handler like this.

For more info, see Handle events by using delegates.

The implementation retrieves the user's name from the text box, uses it to create a greeting, and displays that in the greetingOutput text block.

Build and run the app. Type your name in the text box, and click the button. The app displays a personalized greeting.

Step 3. Style the startup page

Choose a theme

It's easy to customize the look and feel of your app. By default, your app uses resources that have a light-colored style. The system resources also include a dark theme.

To try out the dark theme, edit App.xaml, and add a value for Application::RequestedTheme.

For apps that display mostly images or video, we recommend the dark theme; for apps that contain a lot of text, we recommend the light theme. If you're using a custom color scheme, then use the theme that goes best with your app's look and feel.

Note

A theme is applied when your app starts up. It can't be changed while the app is running.

Use system styles

In this section we'll change the appearance of the text (for example, make the font size larger).

In MainPage.xaml, find the 'What's your name?' TextBlock. Set its Style property to a reference to the BaseTextBlockStyle system resource key.

BaseTextBlockStyle is the key of a resource that's defined in the ResourceDictionary in Program Files (x86)Windows Kits10DesignTimeCommonConfigurationNeutralUAP<version>Genericgeneric.xaml. Here are the property values that are set by that style.

Also in MainPage.xaml, find the TextBlock named greetingOutput. Set its Style to BaseTextBlockStyle also. If you build and run the app now, you'll see that the appearance of both text blocks has changed (for example, the font size is now larger).

Step 4. Have the UI adapt to different window sizes

Now we'll cause the UI to adapt dynamically to a changing window size, and so that it looks good on devices with small displays. To do this, you'll add a VisualStateManager section into MainPage.xaml. You'll define different visual states for different window sizes, and then set the properties to apply for each of those visual states.

Adjust the UI layout

Add this block of XAML as the first child element of the root StackPanel element.

Build and run the app. Notice that the UI looks the same as before until the window is resized narrower than 641 device-independent pixels (DIPs). At that point, the narrowState visual state is applied and, along with it, all of the property setters defined for that state.

The VisualState named wideState has an AdaptiveTrigger with its MinWindowWidth property set to 641. This means that the state is to be applied only when the window width is not less than the minimum of 641 DIPs. You don't define any Setter objects for this state, so it uses the layout properties that you defined in the XAML for the page content.

Visual Studio Hello World Code

The second VisualState, narrowState, has an AdaptiveTrigger with its MinWindowWidth property set to 0. This state is applied when the window width is greater than 0, but less than 641 DIPs. At exactly 641 DIPs, wideState is in effect. In narrowState, you define Setter objects to change the layout properties of controls in the UI.

C# Hello World Visual Studio

  • You reduce the left margin of the contentPanel element from 120 to 20.
  • You change the Orientation of the inputPanel element from Horizontal to Vertical.
  • You add a top margin of 4 DIPs to the inputButton element.

Summary

World

Visual Basic Sample Hello World

This walkthrough showed you how to add content to a Windows Universal app, how to add interactivity, and how to change the UI's appearance.