Skip to content

Instantly share code, notes, and snippets.

@hirosof
Created March 10, 2017 10:37
Show Gist options
  • Save hirosof/286bd82c16207fe33a06a24c8db430e6 to your computer and use it in GitHub Desktop.
Save hirosof/286bd82c16207fe33a06a24c8db430e6 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <Windows.h>
#include <locale.h>
#include <Shlobj.h>
#include <Shobjidl.h>
#include <KnownFolders.h>
void HSOpenFileDialog ( void );
int main ( void ) {
CoInitializeEx ( NULL , COINIT_APARTMENTTHREADED );
setlocale ( LC_ALL , "Japanese" );
HSOpenFileDialog ( );
CoUninitialize ( );
return 0;
}
void HSOpenFileDialog ( void ) {
IFileOpenDialog *pDialog;
//IFileOpenDialog のインスタンスを作成
HRESULT hr = CoCreateInstance ( CLSID_FileOpenDialog , NULL , CLSCTX_INPROC_SERVER , IID_PPV_ARGS ( &pDialog ) );
if ( SUCCEEDED ( hr ) ) {
//タイトル設定
pDialog->SetTitle ( L"ファイルを選択してください。" );
//マイドキュメントのパスを取得する
IShellItem *pFolderPath;
HRESULT hr = SHCreateItemInKnownFolder ( FOLDERID_Documents , KF_FLAG_DEFAULT , NULL , IID_IShellItem , ( void** ) &pFolderPath );
if ( SUCCEEDED ( hr ) ) {
//フォルダをマイドキュメントに設定
pDialog->SetFolder ( pFolderPath );
pFolderPath->Release ( );
}
//ファイルタイプとして1つ設定してそれをデフォルトにする
COMDLG_FILTERSPEC spec;
spec.pszName = L"全てのファイル(*.*)";
spec.pszSpec = L"*.*";
pDialog->SetFileTypes ( 1 , &spec );
pDialog->SetFileTypeIndex ( 1 );
//オプション設定
pDialog->SetOptions ( FOS_PATHMUSTEXIST | FOS_FILEMUSTEXIST | FOS_ALLOWMULTISELECT );
//ダイアログ表示
if ( pDialog->Show ( GetConsoleWindow ( ) ) == S_OK ) {
//以下、選択されたファイル取得
IShellItemArray *pShellArray;
if ( SUCCEEDED ( pDialog->GetResults ( &pShellArray ) ) ) {
DWORD nCount = 0;
pShellArray->GetCount ( &nCount );
IShellItem *pItem;
wchar_t *pPathString;
for ( DWORD i = 0; i < nCount; i++ ) {
if ( SUCCEEDED ( pShellArray->GetItemAt ( i , &pItem ) ) ) {
if ( SUCCEEDED ( pItem->GetDisplayName ( SIGDN_FILESYSPATH , &pPathString ) ) ) {
wprintf ( L"[%u] %s\n" , i + 1 , pPathString );
CoTaskMemFree ( pPathString );
}
pItem->Release ( );
}
}
pShellArray->Release ( );
}
}
pDialog->Release ( );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment