路径显示不下时,中间显示省略号

开发环境:VS2012 C#

//路径显示不下时,中间显示省略号
class CShowShortPath
{
public CShowShortPath(string str)
{
//统一成反斜杠
str = str.Replace('/', '\\');

//收集反斜杆的位置
List<int> indexs = new List<int>();
for (int i = 0; i < str.Length; i++)
{
if ('\\' == str[i])
{
indexs.Add(i);
}
}

//收集可能的显示形式
m_strCanShows.Add(str);
for (int j = indexs.Count / 2, i = j - 1; ; )
{
m_strCanShows.Add(GetShortShow(ref str, ref indexs, i, j));
if ((!ValidIndex(indexs,i)) && (!ValidIndex(indexs,j)) )
{
break;
}
if ((indexs.Count - 1 - j) > (i - 0))
{
j++;
}
else
{
i--;
}
}


}
public List<string> m_strCanShows = new List<string>();
private string GetShortShow(ref string str, ref List<int> indexs, int indexLeft, int indexRight)
{
string str1 = "", str2 = "";
if (ValidIndex(indexs,indexLeft))
{
str1 = str.Substring(0, indexs[indexLeft]);
}
if (ValidIndex(indexs,indexRight))
{
str2 = str.Substring(indexs[indexRight] + 1, str.Length - indexs[indexRight] - 1);
}
return str1 + "..." + str2;
}

private bool ValidIndex( List<int> indexs, int index)
{
return ( index >= 0 ) && ( index < indexs.Count ) ;
}

};

下面的类,根据TextBox的宽度显示文件路径:
public class CShow
{
public static void ShowSinglePathIfNoSpace(string strPath, TextBox txtBox)
{
ImeBase.CShowShortPath show = new ImeBase.CShowShortPath(strPath);
for (int i = 0; i < show.m_strCanShows.Count; i++)
{
int iNeedWidth = TextRenderer.MeasureText(show.m_strCanShows[i], txtBox.Font).Width;
if (txtBox.Width > iNeedWidth)
{
txtBox.Text = show.m_strCanShows[i];
break;
}
}
}
}

上一篇:路径显示不下时,中间显示省略号


下一篇:js点击事件