Category Archives: Windows API

Programming using Windows API

Three Ways to Find Files

Let’ say we have to implement a function that search a folder to recursively find files having an extension from a given list of extensions. This article shows three possible implementations: one using FindFirstFile and FindNextFile WinAPI functions, one using CFileFind MFC class and one using Filesystem Library.

Find files using FindFirstFile and FindNextFile WinAPI functions

Althugh this implementation uses some ATL stuff to make things easier, it appears still quite complicated.

Find files using CFileFind MFC class

Using CFileFind MFC class can make code a little bit shorter and the programmer’s life easier.

Note: IsStringInListNoCase searches a list for a string, not case sensitive. You can find its implementation in the attached demo solution.

Find files using Filesystem Library

Here it is:

Hurray, we did it in just few lines of code! :)
Of course, it can be used in MFC, ATL, Win32 and Console applications, as well.

Demo solution

The demo solution contains three projects, each having one of the above implementations.
Download: Find Files Samples (Visual Studio 2015).zip (15)

Resources and related articles

How to Get Visual C++ Sample Projects (2)

In a previous article I showed how to get Visual C++ sample projects either by using Visual Studio IDE or by downloading from MSDN – Developer Code Samples site. Recently, I found that we can also download an archive containing a very large number of sample projects from GitHub. Pretty cool!
Here is the magic link: Microsoft – Windows Classic Samples.

Using Lambdas in MFC Applications – Part 2: Replacing Callback Functions

According to C++11 Standard, stateless lambdas, i.e. having an empty lambda introducer or capture no variables, are implicitly convertible to function pointers. Visual C++ in Visual Studio 2012 and newer, supports this feature. Moreover, in Visual C++ stateless lambdas are convertible to function pointers with arbitrary calling conventions. This is great if have to deal with Win32 API functions, most of them using __stdcall calling convention.
Let’s begin with two simple examples of enumerating top-level windows, one by using a callback function and the other by using a lambda expression.

Enumerate windows using “classic” callback functions

Usually, for that purpose we declare and implement as callback, a static member function having the signature required by EnumWindows in its first argument.

Notes

  • CALLBACK is defined in Windows SDK as __stdcall.

Enumerate windows using lambda expressions

The same result can be achieved by using a lambda expression. This is somehow simpler because does not require to declare and define a static member function.

Notes

  • as stated in the introduction, there is not necessary to explicitly convert the lambda expression to the function pointer required by EnumWindowsProc (WNDENUMPROC);
  • as stated in the introduction, there is not possible to capture neither local variables, nor this pointer; luckily, like in many other WinAPI callbacks, we can pass the necessary stuff in a parameter of type LPARAM or LPVOID.

Using nested lambda expressions

Let’s say we want to enumerate the top-level windows in a worker thread. We can write something like this:

We have passed lambdas both for callback parameter of AfxBeginThread and EnumWindows. EnumWindows is called in the first lambda body and takes a lambda as well.
This compiles with no problem in x64 builds, but may give a conversion error for the inner lambda in Win32 ones. That’s a little glitch which AFAIK has been fixed in Visual Studio 2015.
However, to be sure it compiles also in Visual Studio 2012/2013 – Win32 builds, we can simply cast explicitly the inner lambda.

Notes

  • x64 builds has no __stdcall calling convention; __stdcall keyword is still accepted but simply ignored by the compiler.
  • of course, we can use lambda expressions in the same way also in ATL applications or C++ programs that use plain WinAPI.

Resources and related articles

How to Check the Windows Version

Let’s say we have to check if our application is running under Windows 8.1 or newer. A “classic” way, often found in legacy code, is to call GetVersion or GetVersionEx.

Using GetVersion

Using GetVersionEx

However, if running under Windows 8.1 the above functions may return FALSE.
Moreover, compiling in Visual Studio 2013 Update 3 or newer, we can get warnings or even errors if SDL checks compiler option (/sdl) is set.

That’s because with the release of Windows 8.1, the behavior of the GetVersion and GetVersionEx has changed. Additionally, the MSDN documentation says that GetVersion and GetVersionEx may be altered or unavailable for releases after Windows 8.1. Instead, we still can use VerifyVersionInfo.

Using VerifyVersionInfo

Much easier and recommended in MSDN documentation, is to use Version Helper functions defined by VersionHelpers.h, which is included in the Windows 8.1 SDK. In our case we can simply call IsWindows8Point1OrGreater.

Using Version Helper functions

Notes

  • We can still use the deprecated GetVersion and GetVersionEx returning correct version under Windows 8.1 by setting Windows 8.1 target in the manifest (see Targeting your application for Windows 8.1 topic in MSDN). However, using Version Helper functions is easier and probably more reliable for the future versions.

Resources and related articles

Tree-View Control – TVS_EX_RICHTOOLTIP style

Windows Vista introduced a buch of extended styles for tree-view control (SysTreeView32). Among them, there is TVS_EX_RICHTOOLTIP style which is described in MSDN documentation as follows: “Allow rich tooltips in the tree view (custom drawn with icon and text)”. This article shows a little bit more about how to set and which is the effect of using this extended style.

How to set and remove TVS_EX_RICHTOOLTIP style

Like the other tree-view extended styles, TVS_EX_RICHTOOLTIP can be set or removed as follows:

Sending TVM_SETEXTENDEDSTYLE message

Using TreeView_SetExtendedStyle macro

Calling CTreeCtrl::SetExtendedStyle (MFC)

Further, let’s use the above code and see what’s happen.

The effect of TVS_EX_RICHTOOLTIP style

By default, if the mouse pointer hovers a partially visible tree item, a tootip containing the item’s text is shown.

Tree item tooltip - TVS_EX_RICHTOOLTIP not set

Tree item tooltip – TVS_EX_RICHTOOLTIP not set

If the TVS_EX_RICHTOOLTIP style is set, then the tooltip displays the item’s icon in addition to the item’s text.

Tree item tooltip - TVS_EX_RICHTOOLTIP set

Tree item tooltip – TVS_EX_RICHTOOLTIP set

Note that TVS_EX_RICHTOOLTIP has no effect if TVS_INFOTIP style is set. In this case, the tooltip shows the text provided in TVN_GETINFOTIP notification handler and no icon. So far, that’s all I found about it. If somebody can reveal more, please do not hesitate to leave a reply!

Downloads

Demo project (Visual Studio 2013) – TVS_EX_RICHTOOLTIP_Demo.zip (553)

Resources

Multiple-View File Explorer

File Explorer (aka Windows Explorer) is a well known and commonly used file manager application, shipped since early Windows 95 operating system. There are also other replacements that can be found over the Internet, however, let’s see how can we make our own file manager, having multiple (tabbed) views.

A brief tour of possible ways

Ones can say that’s a piece of cake: just use raw-WinAPI to populate a tree with folders then a list with folder contents. Another ones can choose to use IShellFolder and browse the shell namespace for the same purpose. Booth methods require a lot of work to do and may be a real overkill. Even more advanced methods like using IShellView and IFolderView are not so easy.
Fortunately, for Windows Vista, Windows Server 2008 and newer Windows versions, we can use IExplorerBrowser interface to get a “full featured” File Explorer.
We have it so let’s use it!

Create the multiple tabbed views application

If have Visual Studio 2008 SP1 or newer, creating such type of project is no sweat.

  • Create a new MFC Application project (Ctrl+Shift+N).
  • In MFC Application Wizard check theese options:
    • Application type: Multiple documents & Tabbed documents
    • Project style: MFC Standard
    • User interface Features: Split window
    • Change generated view class name to CFileExplorerView.
  • Click the “Finish” button.

Of course, you can choose other options, but for our purpose the most important are multiple tabbed documents and split window.

Use IExplorerBrowser interface

We can directly use IExplorerBrowser interface in the view class but to make things easier, I wrote an MFC-extension class named CFileExplorer that takes care of instantiating, releasing and using IExplorerBrowser methods. Here is its definition:

The implementation of CFileExplorer class can be found in the demo project attached to this article. Now, let’s use CFileExplorer in our application view class.

          1. Add a CFileExplorer member to CFileExplorerView class
          2. Handle WM_CREATE message. In the OnCreate handler function, perform browser intialization like creating IExplorerBrowser instance, set initial options, set the parent window and folder options.
          3. Handle WM_SIZE and resize the browser to fit the parent client area.
          4. Handle WM_ERASEBKGND to avoid flickering when the parent view is resized.
          5. Finally, let’s override CView::OnUpdate and browse for a folder.

Demo Project

The demo project uses CFileExplorer to make a simple file manager with multiple views.
Download demo project: Multiple-View File Explorer.zip (1401)

Multiple-View File Explorer

Multiple-View File Explorer

          • to open new views choose File/New menu item, press Ctrl+N or push the “New” button;
          • to split a view choose Window/Split menu;
          • to arrange views side by side drag from view tab caption;
          • to change a view layout push “Organize” then check “Layout” subitems;
          • to change the view style (details, small icons, tiles, etc) push “More options” button.

Notes

          • This article as well as the demo project presents just proof of concepts. It can be improved by adding many other features:
            • navigate back and forward;
            • add more functions to menu / toolbar or use a ribbon;
            • filter the columns to be shown in details view;
            • search;
            • automatically show views side by side;
            • make the layout and other settings persistent between application instances;
            • and so on, and so on.

Resources

 

Listing Windows Known Folders

If the target system is Windows Vista, Windows Server 2008 or newer, enumerating known folders (formerly known as special folders) like Desktop, Documents, Program Files, etc is quite easy by calling GetFolderIds method of IKnownFolderManager interface. It gets an array of all registered known folder IDs (KNOWNFOLDERID). Once having a folder ID, we can call IKnownFolderManager::GetFolder to get an instance of IKnownFolder interface and further get more details.

To make things even easier, I wrote two MFC-extension classes CKnownFolderManager and CKnownFolder, which are wrappers over IKnownFolderManager and IKnownFolder, respectively. Here, let’s just see brief code examples. The implementation details can be found in the attached demo project.

Using CKnownFolderManager to get an array of known folders IDs

Using CKnownFolder to fill a lisbox with known folder names

 

Using CKnownFolder to get special folder details

Demo project

Download: Listing Known Folders Demo.zip (762)

The demo project is a simple MFC dialog-based application that uses CKnownFolderManager and CKnownFolder. In the left side is a lisbox which displays the list of known folders names. For each selected listbox item, the edit control from the right side displays the details (name, category, path, etc). Additionally, if the user pushes the “Browse…” button, a browse for folder dialog is shown, having the selected known folder in the root.

Listing Known Folders

Listing Known Folders

Resources