Category Archives: ATL

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 (51)

Resources and related articles

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

Using Direct2D for Rendering WIC Bitmap Sources

Once having a WIC (Windows Imaging Component) source, we can render it by using GDI, GDI+ or Direct2D. There are many examples over the internet including MSDN Library that describes how to perform this.
This article describes how to use WIC Wrapper Library, which is designed for using WIC without worrying about directly deal with COM interfaces. The sample code as well as attached demo project uses MFC, but WIC Wrapper Library can be used in ATL or raw-Win32 projects, as well.

Let’s see the code, step by step!

  1. Add WIC and Direc2D factoy members to the aplication class.
  2. Create WIC and Direc2D factory instances after initializing OLE libraries.
  3. Release factories befor calling AfxOleTerm.

     
  4. Add WIC bitmap source member to document class then override CDocument::OnOpenDocument and CDocument::DeleteContents. Also add an implementation function that loads the WIC bitmap source from a file.


    Now we have a WIC bitmap source in the document class that will be used in the view class to create a Direct2D bitmap and render it in the view’s window.
  5. Add Direct2D render target and bitmap to the view class
  6. Create a Direct2D render target for the view window.

    A good place to call _CreateDirect2DRenderTarget is in the WM_CREATE message handler.
  7. Resize the Direct2D render target each time is necessary.

    If the render target must fit the view window, then the place to call _Resize2DRenderTarget is the WM_SIZE mesage handler.
  8. Create the Direct2D bitmap from WIC bitmap.

    In our case, the best place to call _CreateDirect2DBitmapFromWICBitmap is the overridden CView::OnUpdate function.
  9. Finally, render the bitmap.

    Of course, in a class derived from CView, the place for calling _RenderD2DBitmap is the overridden CView::OnDraw virtual function.
  10. Remains just few little things to ajust: handle WM_ERASEBKGND and override CScrollView::OnScrollBy. Anyway, you can find all the implementation details in the attached demo application.

Demo application

The demo application is a basic image file viewer that uses WIC Wrapper Library.
Download: WIC Wrapper Library v2_0 and Image Viewer Demo Project.zip (1253) (full WIC Wrapper Library source code is included).

Demo Image Viewer

Demo Image Viewer

Requirements

Resources, related articles, examples and projects

WIC File Open Dialog Using IFileOpenDialog Interface

A previoius article extends CFileDialog MFC class, in order to make a File Open or a File Save dialog that automatically filters files, according to available WIC (Windows Imaging Component) codecs. This article presents how to show a similar File Open dialog using IFileOpenDialog interface. This way, it can be used not only in an aplication that uses MFC, but also in an ATL one, even in a raw Win32 or console application that uses basic ATL stuff.
Let’s see an example.

Using IFileOpenDialog to show a WIC File Open Dialog

Enumerating the WIC decoders

Demo project

The demo project is a simple Win32 console application that uses the above functions.

Download: WIC_File_Open_Dialog_Win32_Demo.zip (627)

WIC File Open Dialog - Demo

WIC File Open Dialog – Demo

 

Notes

  • In a similar way, we can make a File Save dialog using IFileSaveDialog interface.
  • This article presents just proof of concepts. IFileOpenDialog offers much more methods to customize the dialog according to specific needs. And of course, a more elegant job can be done by writing some C++ wrapper class(es).
  • For the future, I intend to integrate WIC File Dialogs in WIC Wrapper Library also presented in this blog.
  • The built-in WIC decoders deal with the following image file formats: BMP, GIF, ICO, JPEG, PNG, TIFF and WMPhoto. However there are many other decoders that can befound over the internet. Just to mention two free ones: Microsoft Camera Codec Pack and Adobe DNG Codec for Windows.

Resources

Free WIC codecs download

See also

WIC Wrapper Library – Version 1.1

WIC Wrapper Library v1.1 has the following:

  • new and completed methods for existing wrapper classes in the previous version;
  • new classes: wic::Bitmap and wic::Palette;
  • a new header containg enums, WicWrapEnums.h.

Download: WIC Wrapper Library [1.1].zip (652)

Example 2: Using wic::ImagingFactory::CreateBitmapFromHICON and wic::Bitmap

The following example is close to the previous one, except that it uses wic::ImagingFactory::CreateBitmapFromHICON to display an icon resource.

Demo Application

The demo application displays an icon resource when no image file is loaded.

Download: WIC Wrapper Library Sample [1.1].zip (640)

WIC Wrapper Library – Sample Application #2

WIC Wrapper Library – Sample Application #2

 

See also

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 (1460)

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 (826)

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