C# How to change font of a label

前端 未结 4 1984
死守一世寂寞
死守一世寂寞 2020-12-09 10:33

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\'.

相关标签:
4条回答
  • 2020-12-09 10:47

    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.

    0 讨论(0)
  • 2020-12-09 11:03

    You need to create a new Font

    mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
    
    0 讨论(0)
  • 2020-12-09 11:04

    You can't change a Font once it's created - so you need to create a new one:

      mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
    
    0 讨论(0)
  • 2020-12-09 11:08

    I noticed there was not an actual full code answer, so as i come across this, i have created a function, that does change the font, which can be easily modified. I have tested this in

    - XP SP3 and 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;
    }
    

    Hint: replace Form to either Label, RichTextBox, TextBox, or any other relative control that uses fonts to change the font on them. By using the above function thus making it completely dynamic.

        /// To call the function do this.
        /// e.g 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.
    }
    

    You can also, if you want a full libary so you dont have to code all the back end bits, you can download my dll from Github.

    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);
    

    Simple.

    0 讨论(0)
提交回复
热议问题