Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing data in Windows file properties dialog when opened by ShellExecuteEx

I want to show the Windows file properties dialog for a file from my C++ code (on Windows 7, using VS 2012). I found the following code in this answer (which also contains a full MCVE). I also tried calling CoInitializeEx() first, as mentioned in the documentation of ShellExecuteEx():

// Whether I initialize COM or not doesn't seem to make a difference.
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

SHELLEXECUTEINFO info = {0};

info.cbSize = sizeof info;
info.lpFile = L"D:\\Test.txt";
info.nShow  = SW_SHOW;
info.fMask  = SEE_MASK_INVOKEIDLIST;
info.lpVerb = L"properties";

ShellExecuteEx(&info);

This code works, i.e. the properties dialog is shown and ShellExecuteEx() returns TRUE. However, in the Details tab, the size property is wrong and the date properties are missing:

Properties window opened via my program

The rest of the properties in the Details tab (e.g. the file attributes) are correct. Strangely, the size and date properties are shown correctly in the General tab (left-most tab).

If I open the properties window via the Windows Explorer (file → right-click → Properties), then all properties in the Details tab are shown correctly:

Properties window opened via Windows Explorer

I tried it with several files and file types (e.g. txt, rtf, pdf) on different drives and on three different PCs (1x German 64-bit Windows 7, 1x English 64-bit Windows 7, 1x English 32-bit Windows 7). I always get the same result, even if I run my program as administrator. On (64-bit) Windows 8.1 the code is working for me, though.

My original program in which I discovered the problem is an MFC application, but I see the same problem if I put the above code into a console application.

What do I have to do to show the correct values in the Details tab on Windows 7? Is it even possible?

like image 359
honk Avatar asked Jan 06 '17 12:01

honk


People also ask

What is ShellExecuteEx?

ShellExecute is the code equivalent of a user double clicking a file icon. It causes Windows to work out what application the document file is associated with, launch the program and have it load the document file.

What dialog box will appear if you want to open the properties of folder?

You can also Alt-click on a file or folder to access its properties. The General tab of the Properties dialog box will provide you with information such as the full path to the file or folder, its size, what application is configured to open it, and the date it was created, last modified, and accessed.

How do you use ShellExecuteEx?

To use ShellExecute or ShellExecuteEx, your application must specify the file or folder object that is to be acted on, and a verb that specifies the operation. For ShellExecute, assign these values to the appropriate parameters. For ShellExecuteEx, fill in the appropriate members of a SHELLEXECUTEINFO structure.

How do I access properties of a file?

To view information about a file or folder, right-click it and select Properties. You can also select the file and press Alt + Enter . The file properties window shows you information like the type of file, the size of the file, and when you last modified it.


1 Answers

As Raymond Chen suggested, replacing the path with a PIDL (SHELLEXECUTEINFO::lpIDList) makes the properties dialog correctly show the size and date fields under Windows 7 when invoked through ShellExecuteEx().

It seems that the Windows 7 implementation of ShellExecuteEx() is buggy since newer versions of the OS do not have an issue with SHELLEXCUTEINFO::lpFile.

There is another solution possible that involves creating an instance of IContextMenu and calling the IContextMenu::InvokeCommand() method. I guess this is what ShellExecuteEx() does under the hood. Scroll down to Solution 2 for example code.

Solution 1 - using a PIDL with ShellExecuteEx

#include <atlcom.h>   // CComHeapPtr
#include <shlobj.h>   // SHParseDisplayName()
#include <shellapi.h> // ShellExecuteEx()

// CComHeapPtr is a smart pointer that automatically calls CoTaskMemFree() when
// the current scope ends.
CComHeapPtr<ITEMIDLIST> pidl;
SFGAOF sfgao = 0;

// Convert the path into a PIDL.
HRESULT hr = ::SHParseDisplayName( L"D:\\Test.txt", nullptr, &pidl, 0, &sfgao );
if( SUCCEEDED( hr ) )
{
    // Show the properties dialog of the file.

    SHELLEXECUTEINFO info{ sizeof(info) };
    info.hwnd = GetSafeHwnd();
    info.nShow = SW_SHOWNORMAL;
    info.fMask = SEE_MASK_INVOKEIDLIST;
    info.lpIDList = pidl;
    info.lpVerb = L"properties";

    if( ! ::ShellExecuteEx( &info ) )
    {
        // Make sure you don't put ANY code before the call to ::GetLastError() 
        // otherwise the last error value might be invalidated!
        DWORD err = ::GetLastError();

        // TODO: Do your error handling here.
    }
}
else
{
    // TODO: Do your error handling here
}

This code works for me under both Win 7 and Win 10 (other versions not tested) when called from a button click handler of a simple dialog-based MFC application.

It also works for console applications if you set info.hwnd to NULL (simply remove the line info.hwnd = GetSafeHwnd(); from the example code as it is already initialized with 0). In the SHELLEXECUTEINFO reference it is stated that the hwnd member is optional.

Don't forget the mandatory call to CoInitialize() or CoInitializeEx() at the startup of your application and CoUninitialize() at shutdown to properly initialize and deinitialize COM.

Notes:

CComHeapPtr is a smart pointer included in ATL that automatically calls CoTaskMemFree() when the scope ends. It's an ownership-transferring pointer with semantics similar to the deprecated std::auto_ptr. That is, when you assign a CComHeapPtr object to another one, or use the constructor that has a CComHeapPtr parameter, the original object will become a NULL pointer.

CComHeapPtr<ITEMIDLIST> pidl2( pidl1 );  // pidl1 allocated somewhere before
// Now pidl1 can't be used anymore to access the ITEMIDLIST object.
// It has transferred ownership to pidl2!

I'm still using it because it is ready to use out-of-the-box and plays well together with the COM APIs.


Solution 2 - using IContextMenu

The following code requires Windows Vista or newer as I'm using the "modern" IShellItem API.

I wrapped the code into a function ShowPropertiesDialog() that takes a window handle and a filesystem path. If any error occurs, the function throws a std::system_error exception.

#include <atlcom.h>
#include <string>
#include <system_error>

/// Show the shell properties dialog for the given filesystem object.
/// \exception Throws std::system_error in case of any error.

void ShowPropertiesDialog( HWND hwnd, const std::wstring& path )
{
    using std::system_error;
    using std::system_category;

    if( path.empty() )
        throw system_error( std::make_error_code( std::errc::invalid_argument ), 
                            "Invalid empty path" );

    // SHCreateItemFromParsingName() returns only a generic error (E_FAIL) if 
    // the path is incorrect. We can do better:
    if( ::GetFileAttributesW( path.c_str() ) == INVALID_FILE_ATTRIBUTES )
    {
        // Make sure you don't put ANY code before the call to ::GetLastError() 
        // otherwise the last error value might be invalidated!
        DWORD err = ::GetLastError();
        throw system_error( static_cast<int>( err ), system_category(), "Invalid path" );
    }

    // Create an IShellItem from the path.
    // IShellItem basically is a wrapper for an IShellFolder and a child PIDL, simplifying many tasks.
    CComPtr<IShellItem> pItem;
    HRESULT hr = ::SHCreateItemFromParsingName( path.c_str(), nullptr, IID_PPV_ARGS( &pItem ) );
    if( FAILED( hr ) )
        throw system_error( hr, system_category(), "Could not get IShellItem object" );

    // Bind to the IContextMenu of the item.
    CComPtr<IContextMenu> pContextMenu;
    hr = pItem->BindToHandler( nullptr, BHID_SFUIObject, IID_PPV_ARGS( &pContextMenu ) );
    if( FAILED( hr ) )
        throw system_error( hr, system_category(), "Could not get IContextMenu object" );

    // Finally invoke the "properties" verb of the context menu.
    CMINVOKECOMMANDINFO cmd{ sizeof(cmd) };
    cmd.lpVerb = "properties";
    cmd.hwnd = hwnd;
    cmd.nShow = SW_SHOWNORMAL;

    hr = pContextMenu->InvokeCommand( &cmd );
    if( FAILED( hr ) )
        throw system_error( hr, system_category(), 
            "Could not invoke the \"properties\" verb from the context menu" );
}

In the following I show an example of how to use ShowPropertiesDialog() from a button handler of a CDialog-derived class. Actually ShowPropertiesDialog() is independent from MFC, as it just needs a window handle, but OP mentioned that he wants to use the code in an MFC app.

#include <sstream>
#include <codecvt>

// Convert a multi-byte (ANSI) string returned from std::system_error::what()
// to Unicode (UTF-16).
std::wstring MultiByteToWString( const std::string& s )
{
    std::wstring_convert< std::codecvt< wchar_t, char, std::mbstate_t >> conv;
    try { return conv.from_bytes( s ); }
    catch( std::range_error& ) { return {}; }
}

// A button click handler.
void CMyDialog::OnPropertiesButtonClicked()
{
    std::wstring path( L"c:\\temp\\test.txt" );

    // The code also works for the following paths:
    //std::wstring path( L"c:\\temp" );
    //std::wstring path( L"C:\\" );
    //std::wstring path( L"\\\\127.0.0.1\\share" );
    //std::wstring path( L"\\\\127.0.0.1\\share\\test.txt" );

    try
    {
        ShowPropertiesDialog( GetSafeHwnd(), path );
    }
    catch( std::system_error& e )
    {
        std::wostringstream msg;
        msg << L"Could not open the properties dialog for:\n" << path << L"\n\n"
            << MultiByteToWString( e.what() ) << L"\n"
            << L"Error code: " << e.code();
        AfxMessageBox( msg.str().c_str(), MB_ICONERROR );
    }
}
like image 124
zett42 Avatar answered Oct 22 '22 17:10

zett42