Shorten a Long Path to Fit a Narrow Area

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. for versioning details.

See also  5 Tips for Working With an Onsite Interpreter

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist