我想显示来自我的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属性错误且缺少日期属性:
详细信息标签中的其他属性(例如文件属性)是正确的。奇怪的是,大小和日期属性在常规标签(最左边的标签)中正确显示。
如果我通过Windows资源管理器打开属性窗口(文件→右键单击→属性),则详细信息选项卡中的所有属性都会正确显示:
我在不同的驱动器和三台不同的PC上尝试了几种文件和文件类型(例如txt,rtf,pdf)(1x德语64位Windows 7,1x英语64位Windows 7,1x英语32位Windows 7的)。我总是得到相同的结果,即使我以管理员身份运行我的程序。在(64位)Windows 8.1上,代码对我有用。
我发现问题的原始程序是MFC应用程序,但如果我将上述代码放入控制台应用程序中,我会看到同样的问题。
如何在Windows 7的详细信息标签中显示正确的值?它甚至可能吗?
答案 0 :(得分:3)
正如Raymond Chen建议的那样,使用PIDL(SHELLEXECUTEINFO::lpIDList
)替换路径会使属性对话框在通过ShellExecuteEx()
调用时正确显示Windows 7下的大小和日期字段。
由于较新版本的操作系统与ShellExecuteEx()
没有问题,因此SHELLEXCUTEINFO::lpFile
的Windows 7实施似乎有问题。
还有另一种解决方案可能涉及创建IContextMenu
的实例并调用IContextMenu::InvokeCommand()
方法。我想这就是ShellExecuteEx()
在幕后所做的事情。向下滚动到解决方案2 ,例如代码。
#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一起使用。
以下代码需要Windows Vista或更高版本,因为我正在使用&#34;现代&#34; 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 );
}
}