Shorten a Long Path to Fit a Narrow Area

When you have to display a long file path in a limited amount of space, you can use a Shell Light Weight API to do the job for you.Create a form with two textboxes (txtShortPath and txtLongPath) and a command button. This code demonstrates the call toPathCompactPath, which is Unicode only:

 Private Declare Function PathCompactPathW _Lib "shlwapi.dll" (ByVal hDC As Long, _ByVal lpszPath As Long, ByVal dx As Long) _As BooleanPrivate Declare Function GetDC Lib "user32" _(ByVal hWnd As Long) As LongPrivate Declare Function ReleaseDC Lib _"user32" ByVal hWnd As Long, ByVal hDC As _Long) As LongPrivate Sub Command1_Click()Dim hDC As LongDim sPath As StringDim nWidth As LongConst MAX_PATH As Long = 260' txtLongPath should contain a long path' to a file, txtShortPath should be narrow' enough that it does not normally display' the long path.hDC = GetDC(txtShortPath.hWnd)sPath = Left$(txtLongPath.Text & _vbNullChar & Space$(MAX_PATH), MAX_PATH)nWidth = Me.ScaleX(txtShortPath.Width, _Me.ScaleMode, vbPixels)If PathCompactPathW(hDC, StrPtr(sPath), _nWidth) ThentxtShortPath.Text = Left(sPath, _InStr(sPath, vbNullChar) - 1)Else' False means it could not be made' that short or the call failedtxtShortPath.Text = "Error"End IfReleaseDC txtShortPath.hWnd, hDCEnd Sub

You can also achieve similar functionality with a DrawText Win-dowsAPI call using the DT_PATH_ELLIPSIS and DT_MODIFYSTRING constants. PathCompactPath requires shlwapi.dll version 4.71 or higher, which ships with Internet Explorer 4. See http://msdn. microsoft.com/library/psdk/shellcc/shell/versions.htm for versioning details.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: