ファイルパスを渡すことができる関数をコーディングしたいと思います。たとえば、次のようになります。
C:\FOLDER\SUBFOLDER\FILE.TXT
そして、ファイルを含むフォルダーで Windows エクスプローラーを開き、フォルダー内のこのファイルを選択します。(多くのプログラムで使用されている "Show In Folder" の概念に似ています。)
これどうやってするの?
Win32 シェル関数を使用しない最も簡単な方法は、/select
パラメーターを指定して explorer.exe を起動することです。たとえば、プロセスの起動
explorer.exe /select,"C:\Folder\subfolder\file.txt"
file.txt が選択された C:\Folder\subfolder への新しいエクスプローラ ウィンドウが開きます。
新しいプロセスを起動せずにプログラムで実行したい場合は、シェル関数を使用する必要があります。SHOpenFolderAndSelectItems
これは、/select
explorer.exe へのコマンドが内部的に使用するものです。これには PIDL を使用する必要があり、シェル API の仕組みに慣れていない場合は、実際の PITA になる可能性があることに注意してください。
/select
これは、@Bhushan と @tehDorf からの提案のおかげでパスをクリーンアップした、アプローチの完全なプログラムによる実装です。
public bool ExploreFile(string filePath) {
if (!System.IO.File.Exists(filePath)) {
return false;
}
//Clean up file path so it can be navigated OK
filePath = System.IO.Path.GetFullPath(filePath);
System.Diagnostics.Process.Start("explorer.exe", string.Format("/select,\"{0}\"", filePath));
return true;
}
パスに複数のスラッシュが含まれている場合にコマンドを実行すると、フォルダーが開かれず、ファイルが適切に選択されません。ファイル パスが次のようになっていることを確認してください。
C:\a\b\x.txt
それ以外の
C:\\a\\b\\x.txt
@Mahmoud Al-Qudsiの回答をフォローアップする。彼が「プロセスを開始する」と言うとき、これが私にとってうまくいきました:
// assume variable "path" has the full path to the file, but possibly with / delimiters
for ( int i = 0 ; path[ i ] != 0 ; i++ )
{
if ( path[ i ] == '/' )
{
path[ i ] = '\\';
}
}
std::string s = "explorer.exe /select,\"";
s += path;
s += "\"";
PROCESS_INFORMATION processInformation;
STARTUPINFOA startupInfo;
ZeroMemory( &startupInfo, sizeof(startupInfo) );
startupInfo.cb = sizeof( STARTUPINFOA );
ZeroMemory( &processInformation, sizeof( processInformation ) );
CreateProcessA( NULL, (LPSTR)s.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInformation );