hon*_*onk 14 c++ windows winapi file-properties shellexecuteex
我想从我的C++代码中显示文件的Windows文件属性对话框(在Windows 7上,使用VS 2012).我在这个答案中找到了以下代码(其中还包含一个完整的MCVE).我也试过CoInitializeEx()先打电话,如文件中所述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);
Run Code Online (Sandbox Code Playgroud)
此代码有效,即显示属性对话框并ShellExecuteEx()返回TRUE.但是,在" 详细信息"选项卡中,size属性错误,并且缺少日期属性:
" 详细信息"选项卡中的其余属性(例如文件属性)是正确的.奇怪的是,大小和日期属性在" 常规"选项卡(最左侧选项卡)中正确显示.
如果我通过Windows资源管理器打开属性窗口(文件→右键单击→属性),则" 详细信息"选项卡中的所有属性都会正确显示:
我尝试了几种文件和文件类型(例如txt,rtf,pdf)在不同的驱动器和三台不同的PC上(1x德国64位Windows 7,1x英语64位Windows 7,1x英语32位Windows 7) .我总是得到相同的结果,即使我以管理员身份运行我的程序.在(64位)Windows 8.1上,代码对我有用.
我发现问题的原始程序是MFC应用程序,但如果我将上述代码放入控制台应用程序中,我会看到同样的问题.
如何在Windows 7 的" 详细信息"选项卡中显示正确的值?它甚至可能吗?
正如 Raymond Chen 所建议的,用PIDL ( )替换路径SHELLEXECUTEINFO::lpIDList可以使属性对话框在通过 调用时正确显示 Windows 7 下的大小和日期字段ShellExecuteEx()。
看来 Windows 7 的实现ShellExecuteEx()存在错误,因为较新版本的操作系统没有SHELLEXCUTEINFO::lpFile.
还有另一种可能的解决方案,涉及创建该方法的实例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
}
Run Code Online (Sandbox Code Playgroud)
当从简单的基于对话框的 MFC 应用程序的按钮单击处理程序调用时,此代码适用于 Win 7 和 Win 10(其他版本未测试)。
如果您设置info.hwnd为(只需从示例代码中NULL删除该行,因为它已经用 0 初始化),它也适用于控制台应用程序。info.hwnd = GetSafeHwnd();在SHELLEXECUTEINFO参考中指出该hwnd成员是可选的。
不要忘记在应用程序启动时和CoInitialize()关闭时强制调用 或 来正确初始化和取消初始化 COM。CoInitializeEx()CoUninitialize()
笔记:
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!
Run Code Online (Sandbox Code Playgroud)
我仍在使用它,因为它可以开箱即用,并且可以与 COM API 很好地配合使用。
以下代码需要 Windows Vista 或更高版本,因为我使用的是“现代” IShellItemAPI。
我将代码包装到一个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" );
}
Run Code Online (Sandbox Code Playgroud)
下面我展示了如何使用ShowPropertiesDialog()CDialog 派生类的按钮处理程序的示例。实际上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 );
}
}
Run Code Online (Sandbox Code Playgroud)