C#如何更改标签的字体
带有标签和“选项”按钮的表单。 通过单击按钮,将打开一个新表单,其中包含2个单选按钮’Font1’和’Font2’,以及两个按钮’Apply’和’Cancel’。 选择其中一个单选按钮并单击“应用”后,将使第一个表单上的标签更改字体。 问题是如何更改字体,如说从Tahoma到Arial或标签的任何其他字体。
应用按钮的选项表单代码,如果单击该按钮将返回dialogresult.ok == true并更改第一个表单上的标签字体:
private void btnApply_Click(object sender, EventArgs e) { if (radioFont1.Checked) { mainForm.lblName.Font.Name = "Arial"; 'wrong attempt } this.DialogResult = DialogResult.OK; }
在第一个表格上声明标签,以便第二个表格可见:
public static Label lblName = new Label();
…
private void mainForm_Load(object sender, EventArgs e) { lblName = lblBarName; }
Font.Name
, Font.XYZProperty
等是readonly,因为Font
是一个不可变对象,所以你需要指定一个新的Font
对象来替换它:
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
检查Font
类的构造函数以获取更多选项。
创建字体后无法更改字体 – 因此您需要创建一个新字体:
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
您需要创建一个新字体
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
我注意到没有实际的完整代码答案,所以当我遇到这个时,我创建了一个function,它确实改变了字体,可以很容易地修改。 我已经测试了这个
– XP SP3和Win 10 Pro 64
private void SetFont(Form f, string name, int size, FontStyle style) { Font replacementFont = new Font(name, size, style); f.Font = replacementFont; }
提示:将Form替换为Label,RichTextBox,TextBox或任何其他使用字体更改字体的相对控件。 通过使用上述function,使其完全动态化。
/// To call the function do this. /// eg in the form load event etc. public Form1() { InitializeComponent(); SetFont(this, "Arial", 8, FontStyle.Bold); // This sets the whole form and // everything below it. // Shaun Cassidy. }
你也可以,如果你想要一个完整的库,所以你不必编写所有后端位代码,你可以从Github下载我的dll。
Github DLL
/// and then import the namespace using Droitech.TextFont; /// Then call it using: TextFontClass fClass = new TextFontClass(); fClass.SetFont(this, "Arial", 8, FontStyle.Bold);
简单。