Category Archives: Uncategorized

DirectComposition in Action – Coming Soon

I’ve been spending a lot of time with DirectComposition lately. DirectComposition is the primary API for the Windows composition engine. DirectComposition in Action is the name of my next Pluralsight course. I’ve also written a series of articles on DirectComposition for MSDN Magazine. The first is scheduled for the May 2014 issue. Here’s a preview of what you can expect. This is a little game I wrote for the kids that illustrates some of the power of DirectComposition and the Windows composition engine.

SQLite with C++

My latest article for Visual Studio Magazine is now online. This concludes the SQLite miniseries. I hope you’ve enjoyed it and do let me know if you’d like to learn more. SQLite is a fantastic little database engine. Here are links to all three articles.

1. Using SQLite with Modern C++

2. SQLite Performance and Prepared Statements

3. SQLite Queries and Primary Keys

I also covered SQLite in 10 Practical Techniques to Power Your Visual C++ Apps and I may do a course devoted to SQLite in the future.

Making a Window DPI-Aware

How do you make a desktop window DPI-aware? Last time I showed you a few approaches to creating a top-level window on the desktop. If you care at all about the appearance of your app then one of the first things you ought to do is make the window DPI-aware. I covered this at length in an article for MSDN Magazine. Here I want to just summarize the most essential ingredients. The first thing to do is tell Windows that your app is per-monitor DPI-aware. The best way is to use a manifest and you can get the scoop on that from my article in MSDN Magazine. Here I’m interested in the code. I’m going to start with the Window class template that I introduced last time as well as the SampleWindow class that derived from it.

The earliest reasonable opportunity to determine the effective DPI for a given window is in its WM_CREATE handler. Once created the window must also respond to the WM_DPICHANGED message so that it can be notified of any changes to the DPI values over time. Here’s an update to the SampleWindow’s MessageHandler to intercept both of these additional messages.

LRESULT MessageHandler(UINT message,
                       WPARAM const wparam,
                       LPARAM const lparam)
{
    if (WM_PAINT == message)
    {
        PaintHandler();
    }
    else if (WM_DPICHANGED == message)
    {
        DpiHandler(wparam);
    }
    else if (WM_CREATE == message)
    {
        CreateHandler();
    }
    else
    {
        return __super::MessageHandler(message,
                                       wparam,
                                       lparam);
    }

    return 0;
}

The original version only responded to the WM_PAINT message. The WM_DPICHANGED message handler receives the new DPI values through its WPARAM while the WM_CREATE does not require any additional information at this point. Let’s start with the CreateHandler method. The first thing it needs to do is determine the monitor nearest the window. Even though the WM_CREATE message is received before the window is visible on the desktop, the window already has its position and size so this is a fine time to call the MonitorFromWindow function to retrieve the monitor that has the largest intersection with my window. Given the window handle, I can call the GetDpiForMonitor function to retrieve the monitor-specific DPI values.

float m_dpiX = 0.0f;
float m_dpiY = 0.0f;

void CreateHandler()
{
    HMONITOR const monitor = MonitorFromWindow(m_window,
                                               MONITOR_DEFAULTTONEAREST);

    unsigned x = 0;
    unsigned y = 0;

    HR(GetDpiForMonitor(monitor,
                        MDT_EFFECTIVE_DPI,
                        &x,
                        &y));

    m_dpiX = static_cast<float>(x);
    m_dpiY = static_cast<float>(y);
}

I’m just using two member variables to keep track of the DPI values for the window and I’m storing the DPI values using floating point since most DPI-aware rendering uses floating point coordinates. So the window begins life with an awareness of the DPI values it ought to use for scaling and rendering but it’s also responsible for keeping those values up to date. That’s the job of the DpiHandler method. It simply extracts the updated DPI values from the message’s WPARAM and updates the same member variables.

void DpiHandler(WPARAM const wparam)
{
    m_dpiX = LOWORD(wparam);
    m_dpiY = HIWORD(wparam);
}

This WM_DPICHANGED handler could technically do the exact same thing as the WM_CREATE handler and look up the monitor and DPI values directly but this is certainly more convenient. And that’s all there is to it. Assuming you’ve configured your manifest correctly you window will always have the correct DPI values to rely on. Until next time…

For more practical advice and examples for writing apps with Visual C++ please check out 10 Practical Techniques to Power Your Visual C++ Apps.

Read the previous installment in this series: Classy Windows

Using Databases on Windows Azure

My latest article for MSDN Magazine is now online.

Using Databases on Windows Azure

This article will get you up to speed with ODBC with modern C++. For more information on accessing databases with C++ and including SQLite and SQL Server, be sure to check out my course 10 Practical Techniques to Power Your Visual C++ Apps.

I’m beginning a new series on the DirectComposition starting next month.

Classy Windows

How do you create a top-level window on the desktop? For some programmers it’s obvious: use MFC’s CWnd or one of its derived classes such as CFrameWnd or CDialog. I gave up on MFC a long time ago. It’s not bad but it’s certainly not what anyone would consider modern C++. Many programmers moved from MFC to ATL with its CWindowImpl class template. This is certainly modern stuff compared to MFC and there’s nothing wrong with ATL’s windowing classes. It’s lightweight and exceedingly flexible. Still, it adopted MFC’s love of macros and this offends the sensibilities of some who prefer their C++ with a minimum of preprocessing.

I don’t prescribe one technique to rule them all. I actually use three different approaches depending on the circumstance. If I’m teaching and need to describe something that just happens to need a window but is otherwise unrelated then I might just use the Windows API directly. If I’m creating a window with lots of controls then I might use ATL’s CWindowImpl so that I can more easily subclass a window and reflect messages to the appropriate class. These two approaches are radically different. The Windows API accommodates a C style of programming whereas ATL is all about classes. Lately I’ve needed a class for convenience but haven’t needed any of the bells and whistles that ATL provides. For that I wrote a simpler window class template that simply takes care of class-ifying the window procedure and that’s about it.

As I often get asked what approach should be taken I’m going to quickly illustrate all three approaches here and you can choose the one that best suits your needs on any given day. Nothing about this is particularly new but you might find it a helpful refresher on how to get a window on the desktop with C++.

The Windows API

The first approach is the most fundamental. First, register a window class by filling in a WNDCLASS structure and calling the RegisterClass function. Next, create a window based on this class with the CreateWindow or CreateWindowEx function. Finally, pump window messages with the GetMessage and DispatchMessage functions. Here’s a simple example.

int __stdcall wWinMain(HINSTANCE module,
                       HINSTANCE,
                       PWSTR,
                       int)
{
    WNDCLASS wc = {};
    wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
    wc.hInstance = module;
    wc.lpszClassName = L”window”;
    wc.style = CS_HREDRAW | CS_VREDRAW;

    wc.lpfnWndProc = [] (HWND   const window,
                         UINT   const message,
                         WPARAM const wparam,
                         LPARAM const lparam) -> LRESULT
    {
        if (WM_PAINT == message)
        {
            // Render . . .
            VERIFY(ValidateRect(window, nullptr));
            return 0;
        }

        if (WM_DESTROY == message)
        {
            PostQuitMessage(0);
            return 0;
        }

        return DefWindowProc(window,
                             message,
                             wparam,
                             lparam);
    };

    RegisterClass(&wc);

    VERIFY(CreateWindow(wc.lpszClassName,
                        L”Window Title”,
                        WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                        CW_USEDEFAULT,
                        CW_USEDEFAULT,
                        CW_USEDEFAULT,
                        CW_USEDEFAULT,
                        nullptr,
                        nullptr,
                        module,
                        nullptr));

    MSG message;

    while (GetMessage(&message,
                      nullptr,
                      0,
                      0))
    {
        DispatchMessage(&message);
    }
}

It’s pretty simple. I’m using a lambda for the window procedure but that’s optional. The point is that there’s nothing classy about this. It’s all just good old C-style programming from top to bottom. Sometimes this is all you need. I find it certainly helps to keep things simple and focused.

ATL’s CWindowImpl

The second approach of using ATL’s CWindowImpl is a little simpler in that you don’t have to fill in a WNDCLASS structure or call CreateWindow directly. But I don’t really regard those as benefits. Inevitably, I want to customize my window’s appearance and behavior and that’s precisely where I’d start. ATL does allow those details to be overridden but it’s a bit less obvious how it’s done. Still, the code is pretty simple and the result is a window class whose instances represent individual windows. The message handlers are member functions and this certainly helps with program structure. ATL also provides a message loop abstraction but you’re not required to use it. Here’s a simple example.

struct Window : CWindowImpl<Window,
                            CWindow,
                            CWinTraits<WS_OVERLAPPEDWINDOW | WS_VISIBLE>>
{
    DECLARE_WND_CLASS_EX(nullptr, 0, -1);

    BEGIN_MSG_MAP(c)
        MESSAGE_HANDLER(WM_PAINT, PaintHandler)
        MESSAGE_HANDLER(WM_DESTROY, DestroyHandler)
    END_MSG_MAP()

    LRESULT PaintHandler(UINT, WPARAM, LPARAM, BOOL &)
    {
        // Render . . .
        VERIFY(ValidateRect(nullptr));
        return 0;
    }

    LRESULT DestroyHandler(UINT, WPARAM, LPARAM, BOOL &)
    {
        PostQuitMessage(0);
        return 0;
    }
};

int __stdcall wWinMain(HINSTANCE,
                       HINSTANCE,
                       PWSTR,
                       int)
{
    Window window;

    VERIFY(window.Create(nullptr,
                         0,
                         L”Window Title”));

    MSG message;

    while (GetMessage(&message,
                      nullptr,
                      0,
                      0))
    {
        DispatchMessage(&message);
    }
}

Again, it’s pretty simple, but a lot is hidden behind various macros. It’s a good approach if you’re building a complex window based on USER32 controls as there is a lot of help for wiring them all up. If you’re building a modern DirectX app then there’s less value in this approach.

A Simple Window Class Template

The final approach involves a simple window class template that I wrote from scratch. There’s nothing particularly exciting here but it solves a pressing problem. How do I marry a window procedure with an instance of a class? Well, if you’ve ever attempted this and thought you might take a peek at what ATL does you may have been left a little discouraged. ATL employs something called a thunk that involves assembly language to basically rewrite the window procedure to accommodate a “this” pointer. This is certainly very efficient but its messy and very error prone.

Instead of assembly language trickery I can simply store the “this” pointer along with the window structure such that I can simply ask for the pointer given a window handle. This is achieved with the SetWindowLongPtr and GetWindowLongPtr functions.

The challenge is figuring out when to store it and when to retrieve it. I tend to use the WM_NCCREATE message, which is one of the earliest messages to arrive, and carries an app-specific value provided to the CreateWindow or CreateWindowEx functions. Here’s a simple example.

template <typename T>
struct Window
{
    HWND m_window = nullptr;

    static T * GetThisFromHandle(HWND window)
    {
        return reinterpret_cast<T *>(GetWindowLongPtr(window,
                                                      GWLP_USERDATA));
    }

    static LRESULT __stdcall WndProc(HWND   const window,
                                     UINT   const message,
                                     WPARAM const wparam,
                                     LPARAM const lparam)
    {
        ASSERT(window);

        if (WM_NCCREATE == message)
        {
            CREATESTRUCT * cs = reinterpret_cast<CREATESTRUCT *>(lparam);
            T * that = static_cast<T *>(cs->lpCreateParams);

            ASSERT(that);
            ASSERT(!that->m_window);

            that->m_window = window;

            SetWindowLongPtr(window,
                             GWLP_USERDATA,
                             reinterpret_cast<LONG_PTR>(that));
        }
        else if (T * that = GetThisFromHandle(window))
        {
            return that->MessageHandler(message,
                                        wparam,
                                        lparam);
        }

        return DefWindowProc(window,
                             message,
                             wparam,
                             lparam);
    }

    LRESULT MessageHandler(UINT   const message,
                           WPARAM const wparam,
                           LPARAM const lparam)
    {
        if (WM_DESTROY == message)
        {
            PostQuitMessage(0);
            return 0;
        }

        return DefWindowProc(m_window,
                             message,
                             wparam,
                             lparam);
    }
};

A class template is not strictly necessary but I prefer to avoid virtual functions whenever possible. Using a class template allows me to hide this boilerplate code in a base class and use compile-time polymorphism to direct messages to derived classes. A derived class can “override” the MessageHandler without using a virtual function. A derived class is also responsible for actually registering and creating the window. I find this far more convenient as I can control the specifics of window registration and creation. It also resides in the class itself and is plain to see. Here’s an example of a concrete window class based on the window class template above.

struct SampleWindow : Window<SampleWindow>
{
    SampleWindow()
    {
        WNDCLASS wc = {};

        wc.hCursor       = LoadCursor(nullptr, IDC_ARROW);
        wc.hInstance     = reinterpret_cast<HINSTANCE>(&__ImageBase);
        wc.lpszClassName = L”SampleWindow”;
        wc.style         = CS_HREDRAW | CS_VREDRAW;
        wc.lpfnWndProc   = WndProc;

        RegisterClass(&wc);

        ASSERT(!m_window);

        VERIFY(CreateWindow(wc.lpszClassName,
                            L”Window Title”,
                            WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                            CW_USEDEFAULT, CW_USEDEFAULT,
                            CW_USEDEFAULT, CW_USEDEFAULT,
                            nullptr,
                            nullptr,
                            wc.hInstance,
                            this));

        ASSERT(m_window);
    }

    LRESULT MessageHandler(UINT message,
                           WPARAM const wparam,
                           LPARAM const lparam)
    {
        if (WM_PAINT == message)
        {
            PaintHandler();
            return 0;
        }

        return __super::MessageHandler(message,
                                       wparam,
                                       lparam);
    }
    
    void PaintHandler()
    {
        // Render . . .
    }
};

Notice how the m_window inherited member is not initialized before calling CreateWindow but is magically initialized once the call returns. This is a form of reentrancy where the window procedure that you’ve just registered is called a number of times before the CreateWindow function even returns. The window class template takes care of wiring this up in its static window procedure so that the derived window class doesn’t need to think about this too much.

Notice also how the sample window handles WM_PAINT but leaves the base class to handle WM_DESTROY as well as any other messages. Just be careful when deriving further classes. If you decide to go down that route then you’d be better off moving the window creation out of the constructor, otherwise message handlers may be called in derived classes before their constructors have completed. This is essentially the same problem as calling virtual functions from a constructor. Fortunately the solution is simple. Just move the window creation out of the constructor as needed. Anyway, for the example above the program’s main function is nice and simple.

int __stdcall wWinMain(HINSTANCE,
                       HINSTANCE,
                       PWSTR,
                       int)
{
    SampleWindow window;
    MSG message;

    while (GetMessage(&message,
                      nullptr,
                      0,
                      0))
    {
        DispatchMessage(&message);
    }
}

And that’s all there is to it. Three different approaches. Pick the one that best meets the needs of your app.

Now that you have a good idea how to create a desktop window perhaps you’ll want to render your app with DirectX.

Read the next installment in this series: Making a Window DPI-Aware

The C Programming Language in Action

My latest Pluralsight course is now available online:

The C Programming Language in Action

This course will provide you with a complete and practical tour of the C programming language and libraries.

C is a systems programming language and sits at the heart of practically every computing device imaginable. It offers unrivaled performance and supports more devices, processors, and micro-controllers than any other language. This course aims to get you up to speed with the C programming language and libraries. You will learn everything from installing popular compilers, how to compile programs at the command prompt, and how to make sense of the C programming language and libraries.

Go and watch it now!

Have you missed one of my previous courses? Master the essentials of COM, DirectX with C++, and 10 Practical Techniques to Power Your Visual C++ Apps.

Write High-DPI Apps for Windows 8.1

My latest article for MSDN Magazine is now online.

Write High-DPI Apps for Windows 8.1

This one was a long time coming. I think I wrote the first draft over a year ago. I hope you enjoy it. It’s a big deal for Windows apps.

It’s also easier to grasp when you can see it in action, so be sure to check out my latest course where I demonstrate writing high-DPI apps from start to finish.

Articles

I’ve published a few more articles over the last month:

Long Filenames in Windows 8 (Visual Studio Magazine)

Windows 8 finally addresses a longstanding issue with its support for long filenames. While the Windows file systems, notably NTFS, have supported long filenames for longer than I can remember, the Windows shell has been stuck with an antiquated limit of 259 characters. This is the effective limit imposed by the infamous MAX_PATH constant. Fortunately, the Windows shell is beginning to support longer paths; and while it doesn’t yet go far enough, it does provide a new set of path management functions that fully support long filenames.

Using Regular Expressions with Modern C++ (MSDN Magazine)

C++11 introduced a long list of features that are in themselves quite exciting, but if all you see is a list of isolated features, then you’re missing out. The combination of these features makes C++ into the powerhouse that many have grown to appreciate. I’m going to illustrate this point by showing you how to use regular expressions with modern C++. The C++11 standard introduced a powerful regular expression library, but if you use it in isolation—using a traditional C++ programming style—you might find it somewhat tiresome. Unfortunately, this is the way that most of the C++11 libraries tend to be introduced. However, there is some merit in such an approach. If you were looking for a concise example of using some new library, it would be rather overwhelming to be forced into comprehending a slew of new language features at the same time. Still, the combination of C++ language and library features really turns C++ into a productive programming language.

Enjoy!