Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Beginner
Nov 29, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 to PathCompactPath, which is Unicode only:
Private Declare Function PathCompactPathW _
Lib "shlwapi.dll" (ByVal hDC As Long, _
ByVal lpszPath As Long, ByVal dx As Long) _
As Boolean
Private Declare Function GetDC Lib "user32" _
(ByVal hWnd As Long) As Long
Private Declare Function ReleaseDC Lib _
"user32" ByVal hWnd As Long, ByVal hDC As _
Long) As Long
Private Sub Command1_Click()
Dim hDC As Long
Dim sPath As String
Dim nWidth As Long
Const 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) Then
txtShortPath.Text = Left(sPath, _
InStr(sPath, vbNullChar) - 1)
' False means it could not be made
' that short or the call failed
txtShortPath.Text = "Error"
End If
ReleaseDC txtShortPath.hWnd, hDC
End Sub

You can also achieve similar functionality with a DrawText Win-dows API 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.
Phil Fresle
Thanks for your registration, follow us on our social networks to keep up-to-date