Monthly Archives: December 2010

Happy New Year and Window Clippings 3 Discount

I haven’t blogged much this month as I’m taking a little break for Christmas. I’ll be resuming the The new C++ for the new Windows series in the New Year. If you haven’t caught up yet here’s the story so far:

Introduction

Part 0 / Putting bugs into buckets

Part 1 / Objects and handles

 

I’m also running a sale on Window Clippings 3 over the next two weeks. If you order now you can get $10 off the regular price.

Happy New Year!

The new C++ for the new Windows / Part 1 / Objects and handles

This is the second article in a new series about C++ for Windows. Last time I defined the approach for dealing with run-time errors. The next topic that must be addressed is the way in which objects defined by the Windows API are handled, so to speak.

The Windows API exposes a dizzying array of resources, devices, algorithms, and other primitives and abstractions. For the most part all of these are treated as objects at some level of the system. Many are kernel objects, meaning they are defined by a block of memory inside the kernel and exposed only indirectly to applications in user-mode. Others live entirely in your application’s address space but usually have some indirect association with one or more kernel objects. Regardless of how and where they are implemented they tend to be exposed to developers either as handles or COM-style interface pointers. In this article I’m going to discuss handles. I’ll deal with interface pointers in an upcoming article.

Think of a handle as an opaque value that uniquely identifies an object within a process. Although handles are usually defined as pointers you can’t manipulate them directly. You certainly shouldn’t try to dereference or increment them. The Windows API provides functions for creating and manipulating the objects behind the handles. I will discuss various types of objects in future articles but for the purpose of introducing objects and handles I’m going to use the relatively simple event kernel object to illustrate how objects and handles are managed.

Events are typically used to signal to a waiting thread that it can resume execution. Since it is a kernel object, an event includes a security descriptor and usage count. The security descriptor describes who is and is not allowed access to the object as well as what operations those users are allowed to perform. The functions that create kernel objects accept a security descriptor but you can simply pass a null pointer for this argument and default security will be applied. The usage count tells the kernel, who actually owns the object, how many outstanding handles refer to the object. In this way the kernel can ensure that a particular object is not destroyed until all of the processes that had access to it have stopped using it.

An event object also includes two Boolean values indicating whether the event is automatically or manually reset as well as whether it is currently signaled. When an auto-reset event is signaled the kernel allows exactly one waiting thread to resume and automatically resets the event. If no threads are waiting on the event then it remains signaled until such time as a thread attempts to wait on it. When a manual-reset event is signaled the kernel allows any and all waiting threads to resume. The event remains signaled until it is manually reset.

Here is how you might create an event using the CreateEvent function:

HANDLE h = CreateEvent(nullptr,  // default security
                       true,     // manual reset
                       false,    // initially not signaled
                       nullptr); // not named

check(nullptr != h);

If the function fails it returns a null pointer in which case you can call GetLastError for more information. The CloseHandle function instructs the kernel that you are finished with the event. Assuming that there are no other open handles the kernel is free to destroy it.

VERIFY(CloseHandle(h));

An event is signaled using the SetEvent function.

check(SetEvent(h));

It can also be manually reset using the ResetEvent function.

check(ResetEvent(h));

Finally, a thread can wait for an event to become signaled using the WaitForSingleObject function. This function returns WAIT_OBJECT_0 if the event is signaled or WAIT_TIMEOUT if the specified timeout elapses before the event is signaled. Technically it can also return WAIT_ABANDONED but that only applies to mutex kernel objects that are shared across processes. The following wait_for_signal helper function comes in handy when waiting for an event to signal.

bool wait_for_signal(HANDLE event,
                     DWORD timeout = INFINITE)
{
    auto result = WaitForSingleObject(event,
                                      timeout);

    if (WAIT_OBJECT_0 == result)
    {
        return true;
    }
    else if (WAIT_TIMEOUT == result)
    {
        return false;
    }
    else
    {
        throw check_failed(GetLastError());
    }
}

If you want to wait as long as it takes then simply use it as follows.

wait_for_signal(h);

Alternatively you may want to simply know whether an event is signaled. In that case just use a zero timeout.

bool signaled = wait_for_signal(h, 0);

Keep in mind that if the handle refers to an auto-reset event then wait_for_signal will cause the event to be reset if it happens to be signaled.

And that’s it for today. Next time I’ll show you how you can safely manage handles in C++ whether on the stack or within containers while getting the compiler to do all of the work for you. Isn’t that what it’s for?

alt

New in Window Clippings 3: Background

Previous version of Window Clippings had little control over how the background behind your selection is captured. Window Clippings 3 has a new tab just for this!

alt

By default Window Clippings will clear the background behind the window and any shadow and produce an image with an alpha channel so that you can blend it to any background you desire.

alt

Alternatively you can choose to clear the background only behind the shadow. This produces a really cool effect. You still get to see the desktop background through your translucent window but the shadow nicely blends into your presentation.

alt

You can of course capture the entire visible background as it is displayed on screen.

alt

Having control over the background of your screenshots is a great way to make your screenshots really stand out!

The new C++ for the new Windows / Part 0 / Putting bugs into buckets

This is the first article in a new series about C++ for Windows. I would have liked to start this series with a somewhat more fun topic but it needs to be said. There are certain prerequisites for starting a project on the right track and one of those is defining the approach for dealing with run-time errors. Many writers avoid talking about error handling when it comes to C++ because there are different approaches and differing views on how it should be done. I would like to say that you can use whatever approach suites you. I must however prepare the way for the remainder of this series and without a consistent way of dealing with errors subsequent articles won’t make sense.

As my approach relies on the Standard C++ Library and in particular the Standard Template Library the use of C++ exceptions is a given. The challenge then is to come up with a rational strategy for handling run-time errors. First I’ll describe what is to be done with exceptions and then how run-time errors in the Windows API are handled.

The first rule of exception handling is to do nothing. Exceptions are for unexpected run-time errors. Don’t throw exceptions you expect to catch. That also means you must not use exceptions for expected failures. If there are no exception handlers then Windows automatically generates an error report, including a minidump of the crash, as soon as an exception is thrown. This provides a perfect snapshot of the state of your application without unwinding the stack. This helps you to get as close to the source of the error as possible when you perform postmortem debugging. If you sign up with the Windows Quality Online Services (Winqual) then Microsoft will even collect these error reports, categorize them and provide them to you at no charge. This is tremendously valuable.

The next step is to clearly distinguish between fatal run-time errors, those that will crash your program, and run-time errors that are expected and that you will handle in your program so that it can continue to run. Some of these will be unique to your application but many will be common to most applications. Keep in mind that unexpected run-time errors that will be reported with exceptions indicate two things. Firstly they may indicate a bug in your application. You assumed the contents of a file is in a certain format when it is not. You expected a folder to exist when it’s actually missing. You sent a message to a window that’s already destroyed. Your algorithm dereferences an invalid iterator. And so on. Secondly they indicate problems outside of your control. Some other factor on the computer causes memory allocations in your application to fail. You fail to get the size of your window’s client area. You fail to write a value to the registry. These types of run-time errors typically point to a bigger problem. In both cases you don’t want your application to continue and an exception that results in an error report is the fastest way to bring your application down so that it doesn’t cause any further harm and lets you debug the problem when the error report arrives.

On the other hand many errors can and should be handled by your application. You may expect writing a value to the registry to succeed but you probably shouldn’t expect reading a value to succeed. Parsing text should be expected to fail. Creating a file may fail if the complete directory structure isn’t already present. And so on. In these cases using exceptions is not usually appropriate. It is usually simpler and more efficient to handle the error directly and as close to the source of the failure as possible.

Now let’s turn our attention to the many functions in the Windows API and the various ways they report run-time errors. The Windows API is unfortunately not very consistent when it comes to reporting run-time errors. You can think of it as having islands of consistency in a sea of inconsistency. There are four common types used for reporting errors explicitly using a return value.

BOOL

Many functions return a BOOL, a typedef of int, indicating either success or failure. It is best to compare the result against 0 rather than 1 since some functions only guarantee that the result will be nonzero upon successful completion. Some but certainly not all of these functions will provide a more descriptive error code that you can retrieve using the GetLastError function upon failure. The values returned by GetLastError can usually be found in the winerror.h header file excluding the HRESULT values.

LONG/DWORD

Different libraries use various typedefs of long and unsigned long including LONG, DWORD, NET_API_STATUS and others to return an error code directly. In most cases success is defined by a 0 return value. These functions typically directly return error codes defined in the winerror.h header file excluding the HRESULT values.

HRESULT/NTSTATUS

Many newer libraries as well as most member functions of COM interfaces use an HRESULT return value to report errors. Some functions that have roots in the Windows Driver Kit use an NTSTATUS return value. Both of these define identical packed error codes. It is not uncommon for values from winerror.h, possibly returned by GetLastError, to be packed inside an HRESULT before returning it to the caller. An HRESULT or NTSTATUS value can have multiple values indicating success and of course multiple values indicating failure. You need to check the documentation for any function that you’re using but in most cases a 0 return value indicates success with negative values indicating failure. Additional values greater than 0 may be defined to distinguish between different variations of success.

A small number of functions have a void return type. This either means that the function cannot fail, usually because whatever resources it relies on have already been allocated, or that any failure will be reported at a later stage. Other return values often imply an error given some sentinel value. This is common in functions that return a handle or pointer to a resource. You just need to read the documentation carefully to determine how to distinguish success from failure as it is not always true that 0 or nullptr alone indicate failure.

Finally for all those internal assumptions in your application there are assertions. Prefer to use static_assert for compile time validation. When that’s not possible use an ASSERT macro that is compiled away in release builds. I prefer to use the _ASSERTE macro from crtdbg.h as it stops the program in the debugger right on the offending line of code.

The listing at the end of this article includes error.h and error.cpp used for error handling in subsequent articles.

Although I avoid macros as much as possible, they remain the only solution for implementing debug assertions. I also define VERIFY and VERIFY_ mainly for checking the result of functions called within destructors where exceptions should not be used. It at least lets me assert the result of these functions in debug builds.

Namespaces are used to partition types and functions unless they’re specifically designed to work together. The error handling functions are however so fundamental that they reside in root kerr namespace. A few overloaded functions are provided for checking the return value of most functions in the Windows API. Argument matching and integral promotion rules help to funnel the various return types into the appropriate check functions. Specifically the int overload handles bool and BOOL return types, the long and unsigned long overloads take care of the rest. The check template function also comes in quite handy when you need to check for a specific value rather than the usual logical success or failure return values.

The check functions throw check_failed exceptions. The check_failed type includes a member that holds the error code passed to the check functions or returned by GetLastError. This comes in handy when you receive a minidump which contains the address of the exception and then allows you to easily find this error code. This can often be invaluable in determining the cause of the crash.

Why did I title this part “Putting bugs into buckets”? Well that’s because Windows Error Reporting categorizes error reports into what they call buckets. And that’s all for today and as always I’d love to hear what you think.

error.h

#pragma once

#ifdef _DEBUG
    #include <crtdbg.h>
    #define ASSERT(expression) _ASSERTE(expression)
    #define VERIFY(expression) ASSERT(expression)
    #define VERIFY_(expected, expression) ASSERT(expected == expression)
#else
    #define ASSERT(expression) ((void)0)
    #define VERIFY(expression) (expression)
    #define VERIFY_(expected, expression) (expression)
#endif

namespace kerr
{
    struct check_failed
    {
        explicit check_failed(long result);

        long error;
    };

    void check(int);
    void check(long);
    void check(unsigned long);

    template <typename T>
    void check(T expected, T actual)
    {
        if (expected != actual)
        {
            throw check_failed(0);
        }
    }
}

error.cpp

#include "Precompiled.h"
#include "error.h"
#include <Windows.h> // for GetLastError

kerr::check_failed::check_failed(long result) :
    error(result)
{
    // Do nothing
}

void kerr::check(int result)
{
    if (!result)
    {
        throw check_failed(GetLastError());
    }
}

void kerr::check(long result)
{
    if (result)
    {
        throw check_failed(result);
    }
}

void kerr::check(unsigned long result)
{
    if (result)
    {
        throw check_failed(result);
    }
}

Next: Objects and handles

New in Window Clippings 3: Favorites

Favorites are a new feature in Window Clippings 3. They allow you to configure Window Clippings in different ways and give each a friendly name that you can quickly switch between without having to constantly change the Window Clippings settings for a particular screenshot.

Favorites

 

All of the tabs above the Favorites tab apply to the favorite currently selected on the Favorites tab. In this example I’ve added a second favorite called Select shape so that I can use a different file naming scheme for those screenshots. Each favorite can of course have a unique set of actions and outputs, visual effects, and more.

The favorite that is selected on the Favorites tab becomes the default and its name appears on the title bar. The default favorite is the one that is run when you click the Create screenshot button or double click the Window Clippings icon in the notification area. It is also the favorite that runs when you use the “wc.exe favorite” command line.

There are a few ways to run an alternative favorite. If Window Clippings is pinned to the Start menu then you can access your favorites there.

Start menu

 

You can also access your favorites from the jump list if Window Clippings is pinned to the taskbar.

Jump list

 

The icon in the notification area also provides a menu with the favorites when you right-click it with your mouse.

Icon

 

Finally, you can also run a favorite using the following command line. This allows you to create your own Explorer shortcuts (and hot keys) for different favorites.

wc favorite /n "Select shape"

 

Favorites help to further reduce the amount of time you spend creating screenshots.

New in Window Clippings 3: File naming

The Save to disk action in previous versions of Window Clippings simply generated a unique file name based on the window title. Many of you asked me for the ability to customize this naming in some way. Window Clippings 3 delivers. Every action now has access to a tokenized name that you define on the File Naming tab.

File Naming

In this example I’ve used the following format:

Sample-<action>-<id> (<wt>)

Here <action>, <id>, and <wt> and tokens that will be replaced just before each action executes to produce a unique file name. Clicking on the button next to the text box displays a popup menu with available tokens and descriptions. In this case <action> is replaced by the name of the action to be executed, <id> is a unique number, and <wt> is the title of the top-most window in your screenshot.

In the following example I’ve added two Save to disk actions that I’ve given distinct names and separated by a Resize action to make a smaller second image.

Actions

Given that I’ve configured both actions to save to the same folder the results of taking a screenshot of the Calculator are as follows:

Results

Notice that <action> has been replaced with Save A and Save B respectively. Notice also that the <id> token just keeps incrementing. This counter is stored in the Window Clippings settings file so you can be sure that it will always give you a unique number as long as you don’t replace your settings file. Finally the <wt> token has been replaced with the window title from the Calculator application.

Currently the Save to disk as well as the Run command actions makes use of the file naming feature. In future, more and more actions will take advantage of it including 3rd party actions that should be available in the 3.1 release.

I encourage you to play around with the file naming feature in combination with actions and outputs. With a variety of tokens at your disposal, the combination of all of these features can provide some interesting functionality.

Window Clippings vs. the Pirates

I have received a few emails from people in possession of pirated license keys for Window Clippings 2 hoping to receive a free license key for Window Clippings 3. I mentioned here on my blog that anyone who bought a 2.x license in the past was eligible for a free upgrade. Unless you actually purchased a license key from http://windowclippings.com (or personally received one from me) you do not have a genuine license key. I never ran any raffles or other competitions involving license key giveaways. If you received one of these license keys then you’ve been duped. Please purchase a genuine license.

I always knew that the licensing in Window Clippings 2 wasn’t going to present any kind of challenge for pirates. I just never realized there would be people who would then go and take advantage of others by acting as if they are in a position to sell or give away these pirated license keys. It’s not going to be that easy for those pirates this time around but I’m sure they’ll find some way around it eventually.