Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

winforms - C# How to change font of a label

A form with a label and a button 'Options'. By clicking the button a new form opens with 2 radio buttons 'Font1' and 'Font2', and two buttons 'Apply' and 'Cancel'. Upon selecting one of the radio buttons and clicking 'Apply' will make the label on the first form change the font face. The problem is how to change the font as in from say Tahoma to Arial or to any other font face of the label.

Options form code for apply button, which if was clicked will return dialogresult.ok == true and change the font of the label on the first form:

private void btnApply_Click(object sender, EventArgs e)
{
    if (radioFont1.Checked)
    {
        mainForm.lblName.Font.Name = "Arial"; 'wrong attempt 
    }
    this.DialogResult = DialogResult.OK;
}

Declaration of the label on first form so that it is visible to second form:

public static Label lblName = new Label();

...

private void mainForm_Load(object sender, EventArgs e)
{
    lblName = lblBarName;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Font.Name, Font.XYZProperty, etc are readonly as Font is an immutable object, so you need to specify a new Font object to replace it:

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

Check the constructor of the Font class for further options.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...