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
Very nice,
Thanks
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.
Ahh, that’s interesting, Mike – just checked the documentation for it and it says
PathSetDlgItemPathinternally usesPathCompactPath.There’s also PathCompactPathEx which takes a character length instead of pixels.