Archive for December 2010
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:
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!
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.
An event is signaled using the SetEvent function.
It can also be manually reset using the ResetEvent function.
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,
if (WAIT_OBJECT_0 == result)
else if (WAIT_TIMEOUT == result)
If you want to wait as long as it takes then simply use it as follows.
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?
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!
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.
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.
You can of course capture the entire visible background as it is displayed on screen.
Having control over the background of your screenshots is a great way to make your screenshots really stand out!
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.
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.
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.
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.
#define ASSERT(expression) _ASSERTE(expression)
#define VERIFY(expression) ASSERT(expression)
#define VERIFY_(expected, expression) ASSERT(expected == expression)
#define ASSERT(expression) ((void)0)
#define VERIFY(expression) (expression)
#define VERIFY_(expected, expression) (expression)
explicit check_failed(long result);
void check(unsigned long);
template <typename T>
void check(T expected, T actual)
if (expected != actual)
#include <Windows.h> // for GetLastError
kerr::check_failed::check_failed(long result) :
// Do nothing
void kerr::check(int result)
void kerr::check(long result)
void kerr::check(unsigned long result)
Next: Objects and handles
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.
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.
You can also access your favorites from the jump list if Window Clippings is pinned to the taskbar.
The icon in the notification area also provides a menu with the favorites when you right-click it with your mouse.
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.
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.
In this example I’ve used the following format:
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.
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:
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.
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.
This is the start of a new series of articles that I’m writing about C++ for Windows. I took some time off from my regular writing schedule to evaluate my approach to Windows programming and gain some actual production experience using the latest iteration of C++ in my new Micro ISV (check out Window Clippings). What I will be presenting here is not the C++ you’ll find in most of the sample code currently found on MSDN. This is not about MFC. This is not even about ATL and WTL that I’ve recommended for years. This is a fresh new approach to Windows programming with C++. I don’t claim that my ideas are unique but I have found in my experience that the techniques that I’ve adopted help improve my productivity and produce better quality code, code that is easier to maintain, more reliable, and helps to enable excellent performance.
With the introduction of Visual C++ 2010 back in April of this year there was an opportunity for me to reconsider the way I develop applications for Windows. One of the unique aspects of C++ is that it is a multi-paradigm programming language. Other programming languages require you to write all your code as classes, or all of it using only functions. They might provide a handful of container types that you’re practically forced to use. Alternatively they might not provide any and force you to write your own. C++ however places no such constraints on its users. Bjarne Stroustrup sums it up nicely:
C++ was designed to support data abstraction, object-oriented programming, and generic programming in addition to traditional C programming techniques … It was not meant to force one particular programming style upon all users.
As the C++ language and the compilers that implement it have evolved and improved over the years different approaches have been popularized for writing Windows programs. To better appreciate these different approaches it is useful to consider the difference between libraries and frameworks.
Using frameworks generally means that you plug in a bit of code into a larger framework to make your application run. Frameworks usually provide a large runtime or considerable infrastructure that you need to embrace in order to take advantage of the framework. Examples of frameworks commonly used to build Windows applications today include the .NET Framework and the older Microsoft Foundation Classes (MFC).
On the other hand using a library generally means that you write your application in whatever way makes sense to you and then plug in a bit of library code to solve a particular problem in your application without dramatically affecting the way your application is written or packaged. Examples of libraries commonly used in Windows applications today include the Active Template Library (ATL) and the Windows Template Library (WTL). Of course there are many others.
There isn’t always a very clear distinction between frameworks and libraries. You can for example use ATL in such a way that it effectively becomes a framework that your code plugs into. Some approaches or libraries might even exclude the use of other libraries. So while its multi-paradigm roots have helped C++ tremendously it has also inadvertently splintered the community of developers into different camps. Many developers cannot imagine using anything other than MFC to build Windows applications. Others swear by ATL and WTL as a more flexible and relatively modern approach.
I’m not here to tell you that any one of these approaches is wrong. That’s the beauty of C++. You get to choose what works for you and your application. I am here to tell you that Visual C++ 2010 provides the building blocks for a different approach that I’ve started using. An approach based on libraries rather than frameworks.
This series is called “The new C++ for the new Windows” because I’m going to show you how you can embrace C++0x, the unofficial new standard for the C++ programming language, and use it to your advantage when writing applications for the new Windows. The “new Windows” is just a cute way to refer to those new and improved libraries in the Windows SDK that target the contemporary versions of Windows namely Windows 7 and Windows Vista. That means I have the luxury of avoiding all that nasty code in existing libraries like MFC and ATL that uses older APIs dating back to Windows 95 when far better alternatives exist today.
And that’s it for my introduction. The first few parts of this series will lay down some foundational principles and then we’ll dig in and look at how they can be used with various parts of the Windows SDK. I’m hoping to publish one installment a week and I’d love to hear what you think.
Most people using Window Clippings seem to appreciate its ability to perfectly capture the shadows produced by Windows itself.
Some people however prefer to capture windows without shadows. This is often preferred in print publications. Although this was supported in previous versions, Window Clippings 3 now also perfectly captures the way that windows are rendered without shadows instead of just cropping the shadow from the image.
Contrast that with this image produced by Window Clippings 2.1 and your eye should be able to pick up the difference. The image above appears softer and more natural because that’s exactly how Windows renders it. This one however appears to have rougher corners.
If we zoom in this becomes somewhat clearer. In the following image the window above and to the right was captured with version 2.1 and the window below it with version 3.
Of course the alpha channel is there if you need it.
The default installer for Window Clippings 3 requires an Internet connection. This can sometimes fail if your Internet connection is very restrictive (proxy servers, firewalls, etc). As an alternative you can download the complete installer for an offline installation here:
This will download a ZIP file that contains the Windows Installer package (WindowClippings.msi) that you can then copy to your desktop and run without requiring an Internet connection.