Created
March 3, 2016 12:05
-
-
Save armornick/106e1124995194af5c02 to your computer and use it in GitHub Desktop.
How to request a file via the Windows API using both the old and new method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <windows.h> | |
#ifdef UNICODE | |
/* | |
IT FUCKING WORKS WITH G++ FUCKING GODDAMIT!!!88!!! | |
g++ -municode -s -static -Os -o openfiledialog-gnu openfiledialog.cpp -lshell32 -luuid -lole32 -DUNICODE -D_UNICODE -D_WIN32_WINNT=_WIN32_WINNT_VISTA -DNTDDI_VERSION=NTDDI_VISTA | |
NOTE: forgive the expletives but it took several days to get this working and it turned out I forgot to define the version macros | |
*/ | |
#include <shobjidl.h> | |
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow) | |
{ | |
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | | |
COINIT_DISABLE_OLE1DDE); | |
if (SUCCEEDED(hr)) | |
{ | |
IFileOpenDialog *pFileOpen; | |
// Create the FileOpenDialog object. | |
hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL, | |
IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileOpen)); | |
if (SUCCEEDED(hr)) | |
{ | |
// Show the Open dialog box. | |
hr = pFileOpen->Show(NULL); | |
// Get the file name from the dialog box. | |
if (SUCCEEDED(hr)) | |
{ | |
IShellItem *pItem; | |
hr = pFileOpen->GetResult(&pItem); | |
if (SUCCEEDED(hr)) | |
{ | |
PWSTR pszFilePath; | |
hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath); | |
// Display the file name to the user. | |
if (SUCCEEDED(hr)) | |
{ | |
MessageBox(NULL, pszFilePath, L"File Path", MB_OK); | |
CoTaskMemFree(pszFilePath); | |
} | |
pItem->Release(); | |
} | |
} | |
pFileOpen->Release(); | |
} | |
CoUninitialize(); | |
} | |
return 0; | |
} | |
#else | |
int WINAPI WinMain( HINSTANCE hInstance , HINSTANCE hPrevInstance , LPSTR lpCmdLine , int nCmdShow ) | |
{ | |
OPENFILENAME ofn ; | |
// a another memory buffer to contain the file name | |
char szFile[100] ; | |
// open a file name | |
ZeroMemory( &ofn , sizeof( ofn)); | |
ofn.lStructSize = sizeof ( ofn ); | |
ofn.hwndOwner = NULL ; | |
ofn.lpstrFile = szFile ; | |
ofn.lpstrFile[0] = '\0'; | |
ofn.nMaxFile = sizeof( szFile ); | |
ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0"; | |
ofn.nFilterIndex =1; | |
ofn.lpstrFileTitle = NULL ; | |
ofn.nMaxFileTitle = 0 ; | |
ofn.lpstrInitialDir=NULL ; | |
ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST ; | |
GetOpenFileName( &ofn ); | |
// Now simpley display the file name | |
MessageBox( NULL , ofn.lpstrFile , "File Name" , MB_OK); | |
return 0; | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment