Search code examples
c++filewinapigetopenfilename

Can't close OPENFILENAME


I use OPENFILENAME and the function GetOpenFileName() to get a file location through the windows file browser.

The problem is when I want to delete the chosen folder (when the program running and I need to do this) windows show an error: "The action can't be completed because the folder or a file in it is open in another program"

I know why it does that but I don't know how to close this file during runtime

Thanks, in advance.

EDIT :

//Opening Save file
    TCHAR *filter = _T("Story File(*.Strory*)\0*.Story*\0");
    HWND owner = NULL;

    OPENFILENAME ofn;
    TCHAR fileName[MAX_PATH] = _T("");
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(OPENFILENAME);
    ofn.hwndOwner = owner;
    ofn.lpstrFilter = filter;
    ofn.lpstrFile = fileName;
    ofn.nMaxFile = MAX_PATH;
    ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
    ofn.lpstrDefExt = _T("");

    if (GetOpenFileName(&ofn))
    {

    }

This code is where I create and use the OPENFILENAME variable, the GetOpenFileName() will automatically lock the chosen file as "open in a program" and prevent any modification of the folder during the runtime of the program (like delete or rename). But I want to disable this property.


Solution

  • if you not use OFN_NOCHANGEDIR flag in OPENFILENAME the GetOpenFileName open handle for directory, where you select file and set it as current directory. exactly this folder handle prevent from delete it. you can use OFN_NOCHANGEDIR flag or before delete folder change current directory for some another. say to windows directory - you not delete it:

    WCHAR path[MAX_PATH];
    GetSystemWindowsDirectoryW(path, RTL_NUMBER_OF(path));
    SetCurrentDirectoryW(path);