Search code examples
c++windowswinapiwindows-shell

How to get focus back when SHBrowseForFolder returns


I'm currently using SHBrowseForFolder() to open a browse folder window but how do I return focus to my main window when Cancel / OK is pressed. I read that I should re-enable my main window before the dialog closes but where is that exactly? Any thoughts?

void buttonPush(HWND hWnd) {
    EnableWindow(hWnd, FALSE);
    BROWSEINFO bi = { 0 };
    TCHAR szDir[MAX_PATH] = { 0 };
    LPITEMIDLIST pid = NULL;
    LPMALLOC pMalloc = NULL;

    if (SUCCEEDED(SHGetMalloc(&pMalloc)))
    {
        ZeroMemory(&bi,sizeof(bi));
        bi.hwndOwner = NULL;
        bi.pszDisplayName = NULL;
        bi.pidlRoot = NULL;
        bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_USENEWUI;
        bi.lpfn = BrowseCallbackProc;

        pidl = SHBrowseForFolder(&bi); 
        if (pidl) 
        { 
            // Folder selected in dialog
            pMalloc->Free(pidl); 
        } 
        pMalloc->Release();
    }
    EnableWindow(hWnd, TRUE);
}

Solution

  • Instead of enabling and disabling your main window, just set bi.hwndOwner = hWnd; Then it will enable and disable automatically.