C# How to change font of a label - c#

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

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.

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

You need to create a new Font
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

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.

this.lblMessage.Font = new Font("arial", this.lblName.Font.Size);

Related

RichTextBox not showing the text

I am trying to create a Bitmap from a RichTextBox and set it as the background image for a panel, but unfortunately the text is not shown.
Bitmap l_bitmap = new Bitmap(m_control.Width, m_control.Height);
m_control.DrawToBitmap(l_bitmap, new Rectangle(0, 0, l_bitmap.Width, l_bitmap.Height));
m_panel.BackgroundImage = l_bitmap;
m_panel.Refresh();
m_control is my RichTextBox. When I debug, I can see that the control contains the text I wrote, but the bitmap just shows an empty RichTextBox.
I use the same code for other types of controls (Button, CheckBox, TextBox...). The text is shown with no problems.
Well you are trying to create a bitmap from the control. The text you put in there isn't the control, so it won't bother to chow it as bitmap. Try to create a picture from screen (like a screenshot).
Example:
Graphics gr = Graphics.FromImage(l_bitmap);
gr.CopyFromScreen(m_control.PointToScreen(Point.Empty), point.Empty, m_control.Size);
This will make a bitmap from your given points. This will additional show you the text.
EDIT
Maybe you can use this instead. In addition to your idea, I simply put a label onto my panel. (L for Label and P for Panel)
As you can see, the label is empty because I cleared the Text property. Now, when you click one of the buttons below the panel, it will update the label.Text propertie and there will be the text you gave the control.
Here is some example:
As you can see, the label shows the Name of the control. Completly custom as you can see on my source code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public RichTextBox tmpRtf = new RichTextBox();
//Poor button name incoming...
private void button1_Click(object sender, EventArgs e)
{
if (tmpRtf == null)
tmpRtf = new RichTextBox();
//You can add any text here and it will be shown on the label.
this.tmpRtf.Text = "Richtextbox";
this.UpdatePanel(this.tmpRtf);
}
//Custom method to update the panel for any control. Can pobably be done way better than this, but hey.
private void UpdatePanel(object pControl)
{
//Checks if control is a rtf
if(pControl is RichTextBox)
{
//This is your code! Ay.
Bitmap l_bitmap = new Bitmap(this.panel1.Width / 2, this.panel1.Height / 2);
(pControl as RichTextBox).DrawToBitmap(l_bitmap, new Rectangle(0, 0, l_bitmap.Width, l_bitmap.Height));
this.tmpRtf.BackColor = Color.LightGray;
this.panel1.BackgroundImage = l_bitmap;
this.panel1.BackgroundImageLayout = ImageLayout.Center;
this.labelControlName.Text = this.tmpRtf.Text;
this.panel1.Refresh();
}
}
}
Its not possible to show text on a control thats not visualized. But you can build a workaround! Or, instead of taking a picture you can simply create the control on top of it, that will also show the Text and maybe the user can test it (e.g. click on buttons, look at the control behaviour).
Hopefully this is something to get you inspired that there are always more ways to accomplish.

How to change BackColor to "none" [duplicate]

In my C# Form I have a Label that displays a download percentage in the download event:
this.lblprg.Text = overallpercent.ToString("#0") + "%";
The Label control's BackColor property is set to be transparent and I want it to be displayed over a PictureBox. But that doesn't appear to work correctly, I see a gray background, it doesn't look transparent on top of the picture box. How can I fix this?
The Label control supports transparency well. It is just that the designer won't let you place the label correctly. The PictureBox control is not a container control so the Form becomes the parent of the label. So you see the form's background.
It is easy to fix by adding a bit of code to the form constructor. You'll need to change the label's Parent property and recalculate it's Location since it is now relative to the picture box instead of the form. Like this:
public Form1() {
InitializeComponent();
var pos = label1.Parent.PointToScreen(label1.Location);
pos = pictureBox1.PointToClient(pos);
label1.Parent = pictureBox1;
label1.Location = pos;
label1.BackColor = Color.Transparent;
}
Looks like this at runtime:
Another approach is to solve the design-time problem. That just takes an attribute. Add a reference to System.Design and add a class to your project, paste this code:
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design; // Add reference to System.Design
[Designer(typeof(ParentControlDesigner))]
class PictureContainer : PictureBox {}
You can just use
label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent; // You can also set this in the designer, as stated by ElDoRado1239
You can draw text using TextRenderer which will draw it without background:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
TextRenderer.DrawText(e.Graphics,
overallpercent.ToString("#0") + "%",
this.Font,
new Point(10, 10),
Color.Red);
}
When overallpercent value changes, refresh pictureBox:
pictureBox1.Refresh();
You can also use Graphics.DrawString but TextRenderer.DrawText (using GDI) is faster than DrawString (GDI+)
Also look at another answer here and DrawText reference here
For easy for your design.
You can place your label inside a panel. and set background image of panel is what every image you want. set label background is transparent
After trying most of the provided solutions without success, the following worked for me:
label1.FlatStyle = FlatStyle.Standard
label1.Parent = pictureBox1
label1.BackColor = Color.Transparent
You most likely not putting the code in the load function. the objects aren't drawn yet if you put in the form initialize section hence nothing happens.
Once the objects are drawn then the load function runs and that will make the form transparents.
private void ScreenSaverForm_Load(object sender, EventArgs e)
{
label2.FlatStyle = FlatStyle.Standard;
label2.Parent = pictureBox1;
label2.BackColor = Color.Transparent;
}
One way which works for everything, but you need to handle the position, on resize, on move etc.. is using a transparent form:
Form form = new Form();
form.FormBorderStyle = FormBorderStyle.None;
form.BackColor = Color.Black;
form.TransparencyKey = Color.Black;
form.Owner = this;
form.Controls.Add(new Label() { Text = "Hello", Left = 0, Top = 0, Font = new Font(FontFamily.GenericSerif, 20), ForeColor = Color.White });
form.Show();
Using Visual Studio with Windows Form you may apply transparency to labels or other elements by adding using System.Drawing; into Form1.Designer.cs This way you will have Transparency available from the Properties panel ( in Appearance at BackColor ). Or just edit code in Designer.cs this.label1.BackColor = System.Drawing.Color.Transparent;

Windows Forms Transparent TextBox C# Existing solutions don't work

I am creating my textbox programmatically in a console application that builds a form window on the fly. I am trying to get Input boxes such as the textbox to show up invisible but still allow the user to input data such as username and password or any other customisation fields I provide. This is for a game launcher and I am attempting to make it NOT look like a windows component.
I have tried some of the solutions on the post below.
Transparency for windows forms textbox
EDIT: As you can see above I have already cited that this does not solve my issue. I do not use the form designer as it has a nasty habit of deleting my code because I presume "It knows better".
The Accepted answer for that does not work for me as I do not use the form designer and InitializeComponent();
Does not work it just tells me that it is not a function of the component.
I have gotten as far as this.
using System.Windows.Forms;
namespace Launcher_Namespace
{
public class TransparentTextBox : TextBox
{
public TransparentTextBox()
{
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
}
}
}
And in the main body of code that initialises fields
//Initialise Inputs
_username = new TransparentTextBox();
_username.Bounds = new Rectangle(120, 10, 120, 21);
_username.BackColor = Color.Transparent;
_username.BorderStyle = 0;
_username.Visible = false;
But all this has achieved is allow me to set _username.BackColor = Color.Transparent; Without throwing an error. The Input box remains White with no border. I just want to make the background transparent. Even MSDN recomends this solution but It does not work for me. My only solution left is to build a custom Label class that grabs the inputs and reads the key inputs and adds them to the .Text property but I don't want to do this.
The solution in your linked answer works fine. If you're not using the designer it doesn't matter... you can still use the same solution. InitializeComponent() is simply a method that's created by the code generator in the designer file. If you ever want to know what it does to create controls (it can be very informational to have a look) then create a control using the designer and then inspect the .Designer.cs file.
EDIT: It acts a little funny. You can override OnPaint to fix the white background and disappearing text, see below. Not a "finished" implementation, the cursor doesn't seem to know where to go, but this should get you in the right direction.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
for (int i = 0; i < 3; i++)
{
var x = new UserControl1 {Location = new Point(0, i*20)};
this.Controls.Add(x);
}
}
}
public class UserControl1 : TextBox
{
public UserControl1()
{
SetStyle(ControlStyles.SupportsTransparentBackColor |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
BackColor = Color.Transparent;
TextChanged += UserControl2_OnTextChanged;
}
protected override void OnPaint(PaintEventArgs e)
{
var backgroundBrush = new SolidBrush(Color.Transparent);
Graphics g = e.Graphics;
g.FillRectangle(backgroundBrush, 0, 0, this.Width, this.Height);
g.DrawString(Text, Font, new SolidBrush(ForeColor), new PointF(0,0), StringFormat.GenericDefault);
}
public void UserControl2_OnTextChanged(object sender, EventArgs e)
{
Invalidate();
}
}
}
When we use SetStyle(ControlStyles.UserPaint,true) Control Border Doesn't paint. I did this in Textbox. My textbox border style is FixedSingle but after using setstyle with UserPaint Textbox border is not drawn. Textbox appears like border is set to None.

How do I display default text in EditControls?

What is the easiest way to recreate the effect where a text box displays a certain string (in italics and different font) until the user has clicked into the control and/or written his own text into the field? For an example, look at the "search" box at the top right of SO.
I have tried consuming the Paint event:
private void textEdit1_Paint(object sender, PaintEventArgs e)
{
if (textEdit1.Text.Length == 0 && !textEdit1.Focused)
{
textEdit1.Font = new Font(textEdit1.Font, FontStyle.Italic);
textEdit1.Text = "123";
}
else
{
textEdit1.Font = new Font(textEdit1.Font, FontStyle.Regular);
textEdit1.Text = string.Empty;
}
}
However, that's not working. By default, it shows no text, and if I click into it, I seem to get an infinite loop of setting the text to "123" and string.empty, until I give another control focus.
So, is that approach even the best, and if yes, what's the correct 2nd condition instead of .Focused?
Try the TextEdit.Properties.NullValuePrompt property. This property provides the text displayed grayed out when the editor doesn't have focus, and its edit value is not set to a valid value.
First of all, you shouldn't use the paint event, you should use the FocusChanged event if you want to do it by modifying the text property. However, the simplest method is not to modify the text property, but draw a string on top, like this:
private void textEdit1_Paint(object sender, PaintEventArgs e)
{
if (textEdit1.Text.Length == 0 && !textEdit1.Focused)
{
Font some_font = new Font(...parameters go here...);
Brush some_brush = Brushes.Gray; // Or whatever color you want
PointF some_location = new PointF(5,5); // Where to write the string
e.Graphics.WriteString("some text", some_font, some_brush, some_location);
}
}
So, if there is no text, and text box is not focused, draw this string. There are many overloads of the WriteString function, so you can pick which one you want.
You can use the Enter event. Set Text property to "search" for example. Use your font like others reported. Then catch the Enter event and set the Text property to string.empty.
textedit1.Text = "search";
private void textEdit1_Enter(object sender, EnterEventArgs e)
{
textedit1.text = string.empty;
}
But i think the best practice is the NullValuePrompt.

Transparent control over PictureBox

In my C# Form I have a Label that displays a download percentage in the download event:
this.lblprg.Text = overallpercent.ToString("#0") + "%";
The Label control's BackColor property is set to be transparent and I want it to be displayed over a PictureBox. But that doesn't appear to work correctly, I see a gray background, it doesn't look transparent on top of the picture box. How can I fix this?
The Label control supports transparency well. It is just that the designer won't let you place the label correctly. The PictureBox control is not a container control so the Form becomes the parent of the label. So you see the form's background.
It is easy to fix by adding a bit of code to the form constructor. You'll need to change the label's Parent property and recalculate it's Location since it is now relative to the picture box instead of the form. Like this:
public Form1() {
InitializeComponent();
var pos = label1.Parent.PointToScreen(label1.Location);
pos = pictureBox1.PointToClient(pos);
label1.Parent = pictureBox1;
label1.Location = pos;
label1.BackColor = Color.Transparent;
}
Looks like this at runtime:
Another approach is to solve the design-time problem. That just takes an attribute. Add a reference to System.Design and add a class to your project, paste this code:
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design; // Add reference to System.Design
[Designer(typeof(ParentControlDesigner))]
class PictureContainer : PictureBox {}
You can just use
label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent; // You can also set this in the designer, as stated by ElDoRado1239
You can draw text using TextRenderer which will draw it without background:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
TextRenderer.DrawText(e.Graphics,
overallpercent.ToString("#0") + "%",
this.Font,
new Point(10, 10),
Color.Red);
}
When overallpercent value changes, refresh pictureBox:
pictureBox1.Refresh();
You can also use Graphics.DrawString but TextRenderer.DrawText (using GDI) is faster than DrawString (GDI+)
Also look at another answer here and DrawText reference here
For easy for your design.
You can place your label inside a panel. and set background image of panel is what every image you want. set label background is transparent
After trying most of the provided solutions without success, the following worked for me:
label1.FlatStyle = FlatStyle.Standard
label1.Parent = pictureBox1
label1.BackColor = Color.Transparent
You most likely not putting the code in the load function. the objects aren't drawn yet if you put in the form initialize section hence nothing happens.
Once the objects are drawn then the load function runs and that will make the form transparents.
private void ScreenSaverForm_Load(object sender, EventArgs e)
{
label2.FlatStyle = FlatStyle.Standard;
label2.Parent = pictureBox1;
label2.BackColor = Color.Transparent;
}
One way which works for everything, but you need to handle the position, on resize, on move etc.. is using a transparent form:
Form form = new Form();
form.FormBorderStyle = FormBorderStyle.None;
form.BackColor = Color.Black;
form.TransparencyKey = Color.Black;
form.Owner = this;
form.Controls.Add(new Label() { Text = "Hello", Left = 0, Top = 0, Font = new Font(FontFamily.GenericSerif, 20), ForeColor = Color.White });
form.Show();
Using Visual Studio with Windows Form you may apply transparency to labels or other elements by adding using System.Drawing; into Form1.Designer.cs This way you will have Transparency available from the Properties panel ( in Appearance at BackColor ). Or just edit code in Designer.cs this.label1.BackColor = System.Drawing.Color.Transparent;

Categories