Search code examples
c++winapipathmfc

Problem using PathCompactPath - losing file name


Sample code:

CString strCompactedPath = L"C:\\Users\\ajtru\\AppData\\Roaming\\Meeting Schedule Assistant\\Workbook-S-140-PublicTalk-WatchtowerStudy-ServiceTalk-Videoconference.xsl";
PathCompactPath(nullptr, strCompactedPath.GetBuffer(_MAX_PATH), 300);
strCompactedPath.ReleaseBuffer();

The result:

...\\Workbook-S-140-PublicTalk-Watchtow...

This is not what I want! I want some of the path stripped and the start / end kept.

I am compiling with C++20, so if there is another way?

I think it is because the file name itself is so long:

Workbook-S-140-PublicTalk-WatchtowerStudy-ServiceTalk-Videoconference.xsl

So 300 or even 500 hundred pixels isn't going to cut it.

My goal?

If the full path will not fit on the title bar then compact with ellipses. I see that 300 or 500 are insufficient.


Solution

  • This is the solution I have come up with which seems to work:

    TITLEBARINFO tbi{};
    tbi.cbSize = sizeof(TITLEBARINFO);
    if (GetTitleBarInfo(&tbi))
    {
        const int buttonWidth = GetSystemMetrics(SM_CXSIZE);
        const int availableWidth = tbi.rcTitleBar.right - tbi.rcTitleBar.left - (3 * buttonWidth);
    
        // Limit the length of the file name by using ellipses ...
        CString strCompactedPath = m_openFilePath;
        PathCompactPath(nullptr, strCompactedPath.GetBuffer(_MAX_PATH), availableWidth);
        strCompactedPath.ReleaseBuffer();
        SetWindowText(strCompactedPath);
    }
    else
    {
        SetWindowText(m_openFilePath);
    }
    

    The documentation for TITLEBARINFO structure states:

    The coordinates of the title bar. These coordinates include all title-bar elements except the window menu.

    So I use the value of GetSystemMetrics(SM_CXSIZE) multiplied by 3 to account for:

    • Minimize
    • Maximize
    • Close