欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-21 17:48:18
开发环境:VS2012 C# //路径显示不下时,中间显示省略号 class CShowShortPath { public CShowShortPath(string str) { //统一成反斜杠 str = str.Replace('/', '\\'); //收集反斜杆的位置 List

开发环境: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;
}
}
}
}