【问题标题】:Missing data in Windows file properties dialog when opened by ShellExecuteEx由 ShellExecuteEx 打开时,Windows 文件属性对话框中缺少数据
【发布时间】:2017-05-21 05:08:40
【问题描述】:

我想显示来自我的 C++ 代码的文件的 Windows 文件属性对话框(在 Windows 7 上,使用 VS 2012)。我找到了以下代码in this answer(其中还包含一个完整的 MCVE)。我也试过先打电话给CoInitializeEx(),正如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);

此代码有效,即显示属性对话框并且ShellExecuteEx() 返回TRUE。但是,在详细信息选项卡中,size属性错误,日期属性缺失:

详细信息选项卡中的其余属性(例如文件属性)是正确的。奇怪的是,General 选项卡(最左侧的选项卡)中正确显示了大小和日期属性。

如果我通过 Windows 资源管理器打开属性窗口(文件 → 右键单击​​ → 属性),那么 详细信息 选项卡中的所有属性都会正确显示:

我在不同的驱动器和三台不同的 PC 上尝试了几种文件和文件类型(例如 txt、rtf、pdf)(1x 德语 64 位 Windows 7、1x 英语 64 位 Windows 7、1x 英语 32 位Windows 7的)。即使我以管理员身份运行我的程序,我总是得到相同的结果。不过,在(64 位)Windows 8.1 上,代码对我有用。

我发现问题的原始程序是一个 MFC 应用程序,但如果我将上述代码放入控制台应用程序,我会看到同样的问题。

如何在 Windows 7 的 详细信息 选项卡中显示正确的值?有没有可能?

【问题讨论】:

  • 关于全部细节,所有三个 Windows 都是德文版?对我感兴趣的问题点赞。
  • 有趣。 FWIW 我可以使用here 之类的简单测试在德语 Windows 7(使用英语 UI 语言)上重现此内容。
  • 一个疯狂的猜测 - 我目前没有资源来测试它 - 但也许 Explorer 直接使用 IShellItemIShellItem2 (或相关接口),而不是 ShellExecuteEx .也许他们按预期工作。
  • 附注:ShellExecuteEx 文档说您应该致电CoInitializeEx。 (我试过了,但对你的问题没有帮助。)
  • @Codor:我已经尝试使用管理员权限运行我的程序(在我的问题末尾提到)。这似乎没有什么区别。

标签: c++ windows winapi file-properties shellexecuteex


【解决方案1】:

正如 Raymond Chen 建议的那样,将路径替换为 PIDL (SHELLEXECUTEINFO::lpIDList) 会使属性对话框在通过 ShellExecuteEx() 调用时正确显示 Windows 7 下的大小和日期字段。

ShellExecuteEx() 的 Windows 7 实现似乎有问题,因为较新版本的操作系统不存在 SHELLEXCUTEINFO::lpFile 的问题。

还有另一种可能的解决方案,涉及创建IContextMenu 的实例并调用IContextMenu::InvokeCommand() 方法。我想这就是ShellExecuteEx() 在幕后所做的。向下滚动到 Solution 2 示例代码。

解决方案 1 - 使用带有 ShellExecuteEx 的 PIDL

#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
}

当从简单的基于对话框的 MFC 应用程序的按钮单击处理程序调用时,此代码在 Win 7 和 Win 10(其他版本未测试)下都适用于我。

如果您将info.hwnd 设置为NULL,它也适用于控制台应用程序(只需从示例代码中删除行info.hwnd = GetSafeHwnd();,因为它已经用0 初始化)。在SHELLEXECUTEINFO 参考中指出hwnd 成员是可选的。

不要忘记在应用程序启动时强制调用 CoInitialize()CoInitializeEx() 并在关闭时强制调用 CoUninitialize() 以正确初始化和取消初始化 COM。

注意事项:

CComHeapPtr 是一个包含在 ATL 中的智能指针,它会在作用域结束时自动调用 CoTaskMemFree()。它是一个所有权转移指针,其语义类似于已弃用的std::auto_ptr。也就是说,当你将一个CComHeapPtr对象赋值给另一个对象,或者使用带有CComHeapPtr参数的构造函数时,原来的对象会变成一个NULL指针。

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!

我仍在使用它,因为它可以开箱即用,并且可以与 COM API 配合使用。


解决方案 2 - 使用 IContextMenu

以下代码需要 Windows Vista 或更高版本,因为我使用的是“现代”IShellItem API。

我将代码包装到一个函数ShowPropertiesDialog() 中,该函数接受一个窗口句柄和一个文件系统路径。如果发生任何错误,该函数将抛出一个std::system_error 异常。

#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" );
}

下面我展示了一个如何从 CDialog 派生类的按钮处理程序中使用ShowPropertiesDialog() 的示例。其实ShowPropertiesDialog() 是独立于 MFC 的,因为它只需要一个窗口句柄,但是 OP 提到他想在 MFC 应用程序中使用代码。

#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 );
    }
}

【讨论】:

  • 当然。它在 Win 7 x64 和 Win 10 x64 上对我有用。我至少可以提供基本的错误处理/清理,但目前我也没有太多时间,所以我希望示例代码对你来说是可以的。
  • 我认为你不必走这么远。我认为您可以获取 pidl 并将其设置在 SHELLEXECUTEINFO.lpIDList 中。传递显式 IDList 意味着 shell 将直接使用它,而不是尝试创建一个简单的。
  • @zett42:您知道您的代码是否也适用于控制台应用程序?我把它放到一个测试控制台应用程序中,但属性对话框没有显示给我。但是,所有函数都返回 S_OK 并且所有返回的指针似乎都是有效的句柄。但是,对于 eaten 值,返回 0。对于hwnd,我在控制台窗口标题上尝试了NULLFindWindow() 的返回值。我在这里错过了什么吗?原谅我笨!我稍后会在我的 MFC 程序和lpIDList 的想法中尝试它。
  • @honk 也许它需要一个真正属于您的进程的窗口。您不拥有控制台窗口 it belongs to csrss.exe。您需要此代码的实际应用程序是控制台还是您只是将其用于快速测试?
  • @zett42 CoTaskMemFree 是释放 COM 组件之间传递的内存的标准方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-15
  • 2016-03-14
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
相关资源
最近更新 更多