Remove FontStyle Bold from a Control's Font - c#

I feel like a real noob posting this, but I can't seem to find anything for this...
I have a control that I'm basically trying to toggle the fontstyle between bold and not bold. This should be simple...
However, you can't acccess the Control.Font.Bold property as it is read only, therefore, you need to change the Font property.
To make it bold, I just do this:
this.btn_buttonBolding.Font = new Font(this.btn_buttonBolding.Font, FontStyle.Bold);
Not ideal, but it works. However, how do I go about removing this bold style (once it is bold already)?
I looked hard for duplicates; closest I could find was this, but it doesn't quite answer my situation:
Substract Flag From FontStyle (Toggling FontStyles) [C#]
And this which gives how to set it, but not remove it: Change a font programmatically
Am I missing a simple constructor for the font that could do this? Or am I just missing something easier?

I know this is a bit old, but I was faced with the exact same problem and came up with this:
Font opFont = this.btn_buttonBolding.Font;
if(value)
{
this.btn_buttonBolding.Font = new Font(opFont, opFont.Style | FontStyle.Bold);
}
else
{
this.btn_buttonBolding.Font = new Font(opFont, opFont.Style & ~FontStyle.Bold);
}
The magic is in the "~" which is the bitwise NOT. (See the MSDN KB article "~Operator")
VB.NET version:
Dim opFont As Font = me.btn_buttonBolding.Font
If (value)
me.btn_buttonBolding.Font = new Font(opFont, opFont.Style Or FontStyle.Bold)
Else
me.btn_buttonBolding.Font = new Font(opFont, opFont.Style And Not FontStyle.Bold)
End if

The FontStyle enum contains 5 distinct values.
The one that reset your previous set is FontStyle.Regular
Regular Normal text.
Bold Bold text.
Italic Italic text.
Underline Underlined text.
Strikeout Text with a line through the middle.
It's a bitwise enum where Regular is 0. So setting this value alone reset all other flags

Try this:
private void btn_buttonBolding_Click(object sender, EventArgs e)
{
var style = btn_buttonBolding.Font.Bold ? FontStyle.Regular : FontStyle.Bold;
btn_buttonBolding.Font = new Font(this.Font, style);
}

Related

How to make a text in the textbox both bold and italic?

I'm new to C# language. So I've created a form in Visual Studio and there are 3 checkboxes on it named Bold, Italic and Underlined. There is also a textbox. When I check the "Bold" checkbox, it makes my text bold and all the other checkboxes work like this but when I try to check 2 or all of them, only one of them works. Here's the code I wrote for making the text both bold and italic by checking the first and second checkbox and absolutely doesn't work:
if (checkBox1.Checked == true && checkBox2.Checked == true)
{
textBox1.Font = new Font(textBox1.Font, FontStyle.Bold);
textBox1.Font = new Font(textBox1.Font, FontStyle.Italic);
}
I also have a combobox for font size and it works well but when I check the "Bold" checkbox and then change the font size, it goes back to regular font style and doesn't stay bold.
What should I do?
You're setting the font twice rather than combining the values. If you look at the definition of FontStyle you will see that it is a bitfield (it has the flags attribute). Just OR the values. (Note that we use the bitwise OR rather than the Boolean OR)
{
textBox1.Font = new Font(textBox1.Font, FontStyle.Bold | FontStyle.Italic);
}
It would, however, be better to structure your code slightly differently :
FontStyle style;
if (checkBox1.Checked)
{
style = style | FontStyle.Bold;
}
if (checkBox2.Checked)
{
style = style | FontStyle.Italic;
}
textBox1.Font = new Font(style);

Making specific text bold in a string in C# Windows Forms

I want to make part of the text bold in a textbox, for example the textbox contains.
"This is a text box"
So it will be "This is a text box"
How can I do it in C# Windows Forms?
You can do this with the help of FontStyle interface.
Just add a button in your form and name it Bold and create a click event for that.
You have to use RichTextBox for this, you cannot do this with TextBox.
This code will convert the selected text to bold.
private void btnBold_Click(object sender, EventArgs e)
{
FontStyle style = tbMessage.SelectionFont.Style;
if (tbMessage.SelectionFont.Bold)
{
style = style & ~FontStyle.Bold;
btnBold.Font = new Font(btnBold.Font, FontStyle.Regular);
}
else
{
style = style | FontStyle.Bold;
btnBold.Font = new Font(btnBold.Font, FontStyle.Bold);
}
tbMessage.SelectionFont = new Font(tbMessage.SelectionFont, style);
tbMessage.Focus();
}
You cannot do it in a standard TextBox control, you need to use a RichTextBox control with appropriate formatting.
To be clear, you cannot do that in a TextBox. Use a RichTextBox.
In a RichTextBox, start by selecting the desired text by setting the SelectionStart and the SelectionLength properties or let the user select text interactively. Then apply a formatting by setting one of the Selection... properties:
richTextBox1.Text = "This is a text box";
richTextBox1.SelectionStart = 5;
richTextBox1.SelectionLength = 2;
richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);

Font does not support style 'Regular' - using Semibold fonts in C#

I have a TrueType font, which is "Semibold". I try to use that in the following method:
private FontFamily GetFontFamily(string name)
{
PrivateFontCollection pfc = new PrivateFontCollection();
var path = Server.MapPath("~/Static/webfont/" + name + ".ttf");
pfc.AddFontFile(path);
return pfc.Families[0];
}
private Font GetFont(string name, int size,FontStyle style)
{
return new Font(GetFontFamily(name), size, style);
}
Where I provide a name of my font, and it finds the Sentinel-SemiboldItalic.ttf font. As a FontStyle, I have tried to provide any of the options in the .NET framework (regulary, bold, italic, underline and strikeout).
No matter what, I get the following error:
Font 'Sentinel Semibold' does not support style 'Regular'.
What should I do? How to use a semibold font as a font in C#? Also, can I somehow convert my TrueType font to a regular one (if that would fix the issue) ?
As you can read in the answer to this question, each font has its own properties (for example: enabling a Regular Style or not), as provided by the font creator.
By looking at your font (even just by looking at its name), it seems clear that it is a sub-type whose defining characteristics are precisely being (semi-)bold and italic; consequently, it does sound logical to not have the option to remove these features. If you want a non-bold, non-italic version, you should rely on the parent family (Sentinel).
I too faced the same issue like you. And found that even though we are adding the font[.ttf] file, the incorrect font is getting added in privatefontcollection. Hence i found the workaround for this case. This issue will be thrown randomly. So add the font till correct font is added in private font collection.
private FontFamily GetFontFamily(string name)
{
PrivateFontCollection pfc = new PrivateFontCollection();
var path = Server.MapPath("~/Static/webfont/" + name + ".ttf");
pfc.AddFontFile(path);
**while (pfc.FontFamilies != null && pfc.Families.Length > 0 && (pfc.FontFamilies[0] as FontFamily).Name != "YourFontName")
{
pfc.Dispose();
pfc = new PrivateFontCollection();
GetFontFamily();
}
return pfc.Families[0];
}

DataGridView - Suppress all word wrapping

I'm trying to implement a DataGridView that has smaller cell width than autosize does.
If you look really close at a autosized cell you'll notice that there is still some space that is not used to actually display the cell's content.
That's why I started to measure the content's width by myself via TextRenderer and then manually set the column's width.
The initial problem was that a "A" was displayed as "A..." long before the cell was actually "filled". The reason for that was cell.Style.WrapMode set to "nonSet". I was quite happy that DataGridViewTriState.True did work for that "A"-example.
But now I just noticed that if the String has multiple words ("A, B") the DataGridView tries to display the content to several lines long before the cell is actually "filled".
What I'm now looking for is either a way to delete that "padding" of the cell's content or fully suppress the word wrapping on a certain cell/column (= single line without the String's cut off).
Additionally I should admit that there are no hidden blanks on that Strings so trim has no effect at all.
Edit:
I randomly stumbled upon some colleagues code that seems to do kind of what I'm searching.
StringFormat format = new StringFormat(StringFormatFlags.NoClip);
The documentation says that strings have some rectangle around them that is bigger than the string itself. If the rectangle sticks out of the writeable area the string is wrapped. That code snippet suppresses that (default) behaviour.
The only problem is that this solution only seems to work for drawing strings. I didn't find a possibility to assign a stringformat object to a string.
Try This Code
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
dataGridView1.DefaultCellStyle.WrapMode to DataGridView1TriState.True
Hope it helps you
Can you Try this code. That is working in my condition.
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.Value == null)
return;
var s = e.Graphics.MeasureString(e.Value.ToString(), dataGridView1.Font);
if (s.Width > dataGridView1.Columns[e.ColumnIndex].Width)
{
using (
Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
e.Graphics.DrawString(e.Value.ToString(), dataGridView1.Font, Brushes.Black, e.CellBounds, StringFormat.GenericDefault);
dataGridView1.Rows[e.RowIndex].Height = (int)(s.Height * Math.Ceiling(s.Width / dataGridView1.Columns[e.ColumnIndex].Width));
e.Handled = true;
}
}
}

C# Winforms bold treeview node doesn't show whole text

I'm using the following code to make my treenodes bold:
Font font = new Font(tvQuestionSequence.Font, FontStyle.Bold);
foreach (QuestionnaireBuilder_Category cat in categories)
{
TreeNode node = new TreeNode();
node.Text = cat.Description;
node.Name = cat.Id.ToString();
node.NodeFont = font;
tvQuestionSequence.Nodes.Add(node);
}
But the text of the bold nodes is not displayed correctly. The last letter(s) are not shown. How come? And how to solve this problem?
I found this Post when searching through the web because I am facing the exact same problem.
However, appending a white space to the end of the node was not an option, and I found an alternative way that seems to fix the issue.
After setting my node font Bold, all I need to do is reset the node text with the same value.
Here is the Code Sample:
Font boldFont = new Font(treeview.Font, FontStyle.Bold);
node.NodeFont = boldFont;
node.Text = node.Text;
It seems that the node is redrawn after changing the text, which is exactly what I wanted in the first place.
I've found that this is a Windows issue. A workaround for this problem is this:
In the form constructor set the font of the treeview to bold. When adding nodes which must not be bold, change the font to regular:
// Constructor of your form
public Form()
{
InitializeComponent();
Font font = new Font(tvQuestionSequence.Font, FontStyle.Bold);
tvQuestionSequence.Font = font;
}
// Add regular nodes (not bold)
Font font = new Font(tvQuestionSequence.Font, FontStyle.Regular);
TreeNode treeNode = new TreeNode();
treeNode.Text = "Foo";
treeNode.NodeFont = font;
TreeNode parent = tvQuestionSequence.Nodes.Find("parent", true);
parent.Nodes.Add(treeNode);
Simply use treeView.BeginUpdate() before you bold the node then treeView.EndUpdate() after you've bolded the node.
This is a known Windows bug.
The simple solution is just to append an extra space character at the end of your strings. The space character will not be visible, but it will increase the number of pixels needed to draw the string, so the entire string will be visible.
This is all not helping for me.
What DID the trick is making the font a little bigger and bold at DESIGN time.
(In the Properties window)
So make sure you define the treeview with big enough font, then later you can add nodes with smaller font. They will fit.
I do agree with the solution provided. I just want to add to it to shed a little more light on what the problem is.
The treeview has its own font which determines the width of items at the root level. That compensates for the fact that there is only an item height property available and no item width property.
The solution to your problem is to determine what the font of your root node should be, then set the tree to that same font. You can do that at design time also.
Hope that helps someone.
A workaround for this problem is this:
Set the defaul font of treeview to bold in the properties.
And chnage to not bold when you need.
I do the following, I set the DrawNode Event to call, it sets the node to bold and removes the highlighted colour.
You can set any colour you like using the first parameter of the e.Graphics.FillRectangle function.
private void SetNodeBoldWhenSelected(object sender, DrawTreeNodeEventArgs e)
{
if (e.Node == null) return;
var font = e.Node.NodeFont ?? e.Node.TreeView.Font;
if (e.Node.IsSelected)
{
font = new Font(font, FontStyle.Bold);
}
var bounds = new Rectangle( e.Bounds.X,e.Bounds.Y,e.Bounds.Width+20,e.Bounds.Height);
e.Graphics.FillRectangle(SystemBrushes.ControlDarkDark, bounds);
TextRenderer.DrawText(e.Graphics, e.Node.Text, font, bounds, SystemColors.HighlightText, TextFormatFlags.GlyphOverhangPadding);
}
Now when I select a node I get 20 pixels more space, for my font, this works well, one can calculate the "real" size needed but there is no specification stating it needs to do this but you can use Graphics.MeasureString if you feel you need to do that.
Very easy and works fine
treeView1.SelectedNode.NodeFont = new System.Drawing.Font(treeView1.SelectedNode.TreeView.Font, treeView1.SelectedNode.TreeView.Font.Style | FontStyle.Bold);
this.treeView1.SelectedNode.Text += string.Empty;
I realize this is an old thread and it may have been answered. I just ran across this problem as I'm learning to use TreeViews. What worked for me was changing the font size for the entire TreeView to the same size, or bigger than the font of the level you want to bold. The default font size is 8.something. I changed mine to 10, which was the size I wanted my nodes, and the truncating was gone.
What worked for me: Hooking into the load event in the Control's constructor and tweaking the node as explained in BlunT's answer.
public MyControl()
{
InitializeComponent();
_head = new TreeNode();
this.Load += (s, e) =>
{
trvParts.Nodes.Clear();
_head.NodeFont = new Font(trvParts.Font, FontStyle.Bold);
trvParts.Nodes.Add(_head);
_head.Text = "Node Name";
};
}
It's in vb.Net however the solution to re-enter the value of the TEXT field gets around this nicely. As in:
With myNode
Dim myText As String = .Text 'capture the text
.NodeFont = New Font(<name of your treeview>.Font, FontStyle.Bold)
.Text = myText 'reset the text to the original value
End With
Based on MSDN Library, try change your code to:
Font font = new Font(tvQuestionSequence.Font, FontStyle.Bold);
foreach (QuestionnaireBuilder_Category cat in categories)
{
TreeNode node = new TreeNode();
node.Text = cat.Description;
node.Name = cat.Id.ToString();
node.NodeFont = font;
tvQuestionSequence.BeginUpdate(); //added newline here <--
tvQuestionSequence.Nodes.Add(node);
tvQuestionSequence.EndUpdate(); //added newline here <--
}
It work for me

Categories

Resources