当字符串超过一定长度时,截取部分并添加“...”:
1 private string CutString(string s, Font font, int Width) 2 { 3 string cutStr = ""; 4 for (int i=1; i<= s.Length; i++) 5 { 6 string c = s.Substring(0, i); 7 if (TextRenderer.MeasureText(c, font).Width <= Width) 8 { 9 cutStr = c; 10 } 11 else 12 { 13 break; 14 } 15 } 16 return cutStr; 17 } 18 19 private string GetOmitString(string s, Font font, int MaxWidth) 20 { 21 if (s != null) 22 { 23 int width = TextRenderer.MeasureText(s, font).Width; 24 if (width > MaxWidth) 25 { 26 int pointWidth = TextRenderer.MeasureText("...", font).Width; 27 return CutString(s, font, MaxWidth - pointWidth) + "..."; 28 } 29 else 30 { 31 return s; 32 } 33 } 34 else 35 { 36 return null; 37 } 38 }
测试代码:
1 string s = @"E:\我的软件\Environment\Environment\Environment\Environment\Environment\Environment\Environment\Environment.exe"; 2 lblPath.Text = GetOmitString(s, lblPath.Font, PathMaxWidth);
效果: