The PathCompactPath function

PathCompactPath is a not-so-well-known function that truncates a file path to fit within a specific pixel-width and uses ellipses to show that it’s been truncated. Here’s some sample code that shows how you can use it :-

#ifndef UNICODE
#define _tcout cout
#else
#define _tcout wcout
#endif

void TruncateShow(LPCTSTR buff, UINT pixels)
{
    TCHAR tmpbuff[MAX_PATH*4] = {0};
    _tcsncat(tmpbuff, buff, MAX_PATH*4);
    //While not mentioned in the docs, you can pass NULL for HDC
    if(PathCompactPath(NULL,tmpbuff,pixels))
        _tcout << pixels << _T(" pixel width : ")
        << tmpbuff << endl;
}

int main()
{
    const TCHAR buff[MAX_PATH*4] = _T("C:\\Program Files\\Microsoft")
        _T(" Visual Studio .NET 2003\\Vc7\\lib");
    _tcout << _T("Original string : ") << buff << endl;
    TruncateShow(buff,300);
    TruncateShow(buff,200);
    TruncateShow(buff,100);
    return 42;
}

And here’s the output :-

Original string : C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\lib
300 pixel width : C:\Program Files\Microsoft Visual Studio ...\lib
200 pixel width : C:\Program Files\Microsof...\lib
100 pixel width : C:\Progra...\lib
Advertisements

4 thoughts on “The PathCompactPath function

  1. If you’re displaying a path in a static control, you can use another little-known function, PathSetDlgItemPath, to shorten the string so it fits in the window.

  2. Ahh, that’s interesting, Mike – just checked the documentation for it and it says PathSetDlgItemPath internally uses PathCompactPath.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s