110,536
社区成员
发帖
与我相关
我的任务
分享
//返回字符宽度: controlName-显示控件 font-显示字体 str-显示的字符串
private int GetWidth(String controlName,Font font, String str)
{
int width = -1;
switch (controlName)
{
case "Button":
{
Button btn = new Button();
btn.Font = font;
btn.Text = str;
btn.AutoSize = true;
btn.Visible = false;
this.Controls.Add(btn);
width = btn.Width;
btn.Dispose();
break;
}
case "Label":
{
Label lbl = new Label();
lbl.Font = font;
lbl.Text = str;
lbl.AutoSize = true;
lbl.Visible = false;
this.Controls.Add(lbl);
width = lbl.Width;
lbl.Dispose();
break;
}
// case "...": 这里还可以扩展其它控件,或者找一个接近的代替。
}
return width;
}
// 测试用代码
private void button8_Click(object sender, EventArgs e)
{
Font font = new Font("Verdana", 9, FontStyle.Regular);
MessageBox.Show("Label(中123) 宽:" + GetWidth("Label", "中123", font).ToString());
MessageBox.Show("Button(中123) 宽:" + GetWidth("Button", "中123", font).ToString());
}