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

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

Related

Automatic highlighting a part of the text in a TextBox or RichTextBox

Is it possible to highlight a part of a text without selecting this part of the text preferably with a different color in Textbox or Rich TextBox? In fact, I mean, a part of the text is highlighted by another color differing from the color assigned for text selection. To clarify, I have attached an image showing this behavior. (The image is from a website, not WPF).
The bold and dark green part is a text which is just highlighted, and the gray region is a selected part.
Using the RichTextBox element allows for more styling options which, to my knowledge, aren't available for the regular TextBox element.
Here is an approach that I have created:
// Generate example content
FlowDocument doc = new FlowDocument();
Run runStart = new Run("This is an example of ");
Run runHighlight = new Run("text highlighting in WPF");
Run runEnd = new Run(" using the RichTextBox element.");
// Apply highlight style
runHighlight.FontWeight = FontWeights.Bold;
runHighlight.Background = Brushes.LightGreen;
// Create paragraph
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(runStart);
paragraph.Inlines.Add(runHighlight);
paragraph.Inlines.Add(runEnd);
// Add the paragraph to the FlowDocument
doc.Blocks.Add(paragraph);
// Apply to RichTextBox
YourRichTextBoxHere.Document = doc;
View Screenshot
I found this article to be helpful.
Highlight Searched Text in WPF ListView
While the article is about highlighting searched text in a ListView, I have easily adapted it in my own code to work with pretty much any control.
Starting with the control you pass in, it will recursively look for TextBlocks and will find the text you want, extract it as an inline, and will change it's Background / Foreground properties.
You can easily adapt the code to be a behavior if your want.
Here is an example:
private void HighlightText(object controlToHighlight, string textToHighlight)
{
if (controlToHighlight == null) return;
if (controlToHighlight is TextBlock tb)
{
var regex = new Regex("(" + textToHighlight + ")", RegexOptions.IgnoreCase);
if (textToHighlight.Length == 0)
{
var str = tb.Text;
tb.Inlines.Clear();
tb.Inlines.Add(str);
return;
}
var substrings = regex.Split(tb.Text);
tb.Inlines.Clear();
foreach (var item in substrings)
{
if (regex.Match(item).Success)
{
var run = new Run(item)
{
Background = (SolidColorBrush) new BrushConverter().ConvertFrom("#FFFFF45E")
};
tb.Inlines.Add(run);
}
else
{
tb.Inlines.Add(item);
}
}
}
else
{
if (!(controlToHighlight is DependencyObject dependencyObject)) return;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
{
HighlightText(VisualTreeHelper.GetChild(dependencyObject, i), textToHighlight);
}
}
}
I hope this is helpful!

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

Change label text color RadioButton

My first assignment is to create a program that can dynamically change the text color, alignment etc of a string a user has entered in a text box. Here's my problem: first of all my bold and underline button work, but not the italic one:
label5.Font = new Font(label5.Font.Name, label5.Font.Size, label5.Font.Style ^ FontStyle.Italic);
Secondly, I Have to use Radiobuttons to change my text color, and have managed to do this button per button but I wanted to make it more efficient by making a single procedure that would use my radiobutton's name to change the font, here's what I mean:
protected void Colorchange(object sender, EventArgs e)
{
RadioButton selectedRadioButton = (RadioButton)sender;
selectedRadioButton.Name = sender.ToString();
label5.ForeColor = Color.???????; <---Can't figure how to put the name string here....
}
Changed, due your comment:
label5.ForeColor = System.Drawing.Color.Red
//or other option:
label5.Style.Add("color", "Red");
change italic:
label5.Font.Italic = true;
//or other option
label5.Style.Add("font-style", "italic");
the second option in case you want to pass string as you described.
What you search is:
Color red = Color.FromName("Red");
Color blue = Color.FromName(label5.Name);
To change the color of text in TextBox use following code
textBox1.ForeColor=System.Drawing.Color.Green // or choose any color from dropdown
You can do same fo label.
label5.ForeColor=System.Drawing.Color.Red // or any color

Remove FontStyle Bold from a Control's Font

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

Temperature TextBox In C#

I need some code to convert standard C# TextBox to temperature TextBox which means adding "°C" to end of the text in the textbox with another color than the default color.
To get the degree symbol you can use character code 176 e.g.
Char degree = (Char)176
You can then append this to your textbox content or I would just add a label to the right of the textbox with the degree symbol if you want to control the forecolor easily.
TextBox is a plain text editor. To get different colours you would have to muck around with a rich text box. Why not put the "°C" in a label positioned to the right of the text box? That would also make your parsing and rendering code much easier.
You could probably create your own control which inherits from TextBox and then override Text property to automaticaly add °C though other color inside the same TextBox could be problem.
Why you want to have °C in TextBox ?
Can't it just be label right after TextBox ?
You can set static text and color to what you want.
The other solutions proposed here are probably sufficient for your application; however, if you had the need to implement this with re-usability in mind, here is a custom control solution which you may extend to better suit your application:
public class TemperatureTextBox : ContainerControl
{
private const int BORDER_SIZE = 1;
// Exposes text property of text box,
// expose other text box properties as needed:
public override string Text
{
get { return textBox.Text; }
set { textBox.Text = value; }
}
private TextBox textBox = new TextBox()
{
Text = string.Empty,
BorderStyle = BorderStyle.None,
Dock = DockStyle.Fill
};
private Label label = new Label()
{
Text = "°C",
TextAlign = ContentAlignment.MiddleCenter,
Size = new Size()
{
Width = 32
},
BackColor = SystemColors.Window,
Dock = DockStyle.Right
};
public TemperatureTextBox()
{
this.BackColor = SystemColors.Window;
this.Padding = new Padding(BORDER_SIZE);
this.Controls.Add(label);
this.Controls.Add(textBox);
this.PerformLayout();
}
// Constrain control size to textbox height plus top and bottom border:
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
this.Height = (textBox.Height + (BORDER_SIZE * 2));
}
// Render a border around the control:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawRectangle(
SystemPens.ControlDarkDark,
new Rectangle()
{
Width = (this.Width - BORDER_SIZE),
Height = (this.Height - BORDER_SIZE)
});
}
}
Simply create a new class and drop this code in and rebuild you solution. It will create a new TemperatureTextBox control in the toolbox which can be dropped onto a new form and visually designed.
This example exposes the Text property of the underlying text box by overriding the custom control's text property. You may want to expose other properties, and events depending on what your application needs to accomplish.

Categories

Resources