Change text color of existing text - c#

I've written an application that has a richtextbox in it with a black background. Therefore I have to write in it using white text. That all works fine by setting the fore color to white. If I however copy text from Word that is black into my textbox, that text remains black.
I need to change the color of that text. So this is what i've tried so far: (the textbox is named txtMessage)
txtMessage.ForeColor = Color.White;
That doesn't have any effect on the existing black text though.
Then I tried this:
private void txtMessage_TextChanged(object sender, EventArgs e)
{
int s = txtMessage.SelectionStart;
txtMessage.SelectAll();
txtMessage.SelectionColor = Color.White;
txtMessage.Select(s, 0);
}
It in principle works fine but of course every time I edit the text in the textbox (not copying something in there, but simply typing) the whole thing is executed with every letter I type resulting in a flickering ( I guess because all is selected and then deselected every single time).
So does anyone have a suggestion how to fix this elegantly?
Thank you very much.

If you are typing in the box an the colour is set to white, there is no need to run the code.
You only need to run it when you add text that you haven't typed (eg copy/paste from your example).
Therefore, use that code in the TextChanged event, but perform a check before running it as to whether the user has typed the text or added it another way
EDIT: Check the answer to this question: Detecting a paste into a RichTextBox, it might help you

Related

C# How do you set richtextbox text to default?

When some one puts a highlighted sentence to my richtextbox.
For example,
I want to make them type default text if they want to. Let's say if user clicks a button and want it to make default text. How do I do that?
I have tried
Font arialFont = new Font("Arial", 10, FontStyle.Regular);
richTextBox1.SelectAll();
richTextBox1.SelectionFont = arialFont;
richTextBox1.BackColor = Color.White; // i also tried Color.Transparent but it only return error message "Control does not support transparent background colors"
// RichTextBox's property says that Appearance - BackColor - Window, but it didn't even exist on Color.~
How can I set text all in default state in RichTextBox?
I'm sorry for unclear question.
when a user copies a text that is hightlighted text like above picture. And if they keep type anything, the text is highlighted too. But I don't want that to happen.
So I want to make a button to clear all text and make them to type a default text(no highlight, bold, italic, etc...)
I hope I explained my problem well this time. Sorry for unclear question.
Thank you LarsTech, sorry for my poor English. But I kind of solved the problem by doing richTextBox1.SelectionBackColor = Color.Transparent;
I didn't know about Selection has a lot of different function. Probably from next time, I need to look for more functions that's already in it.
Thank you for the hint and have a nice day!

Inserting graphics into RichTextBox

I have just started studying at an university and came up with an idea to manage my transcripts. It's basically a text editor with a small versioning system wrapped around it.
To avoid ending up with walls of black and white text I had the idea to add some presets for "graphics" (not sure what is the right word to use here). For example, if my professor writes down some kind of definition like this one:
Integral
Also called Riemann integral. the numerical measure of the area
bounded above by the graph of a given function, below by the x -axis, and on .........
I would like to wrap it into some kind of different background and styling, just like here on StackExchange on the quote above, with the press of a button. Another example is in one of my books:
Is it even possible to include such styling into a RichTextBox or should I look for alternatives / existing text editors?
Yeah, implementation Example is given to this URL Stack Overflow Answer
and some code for knowledge purpose
//Apply Some Font to selection
richTextBox1.SelectionFont = new Font("Arial", 16);
// Apply same color of text
richTextBox1.SelectionColor = Color.Purple;
//backgroud colour of Selection
richTextBox1.SelectionBackColor = Color.Red;
One more thing is to clearify, if you want to make a text editor, you have to given combo box for colour, size etc, and change this on IndexChange Event.

C# RichTextBox how to change font ForegroundColor upon printing?

I'm trying to use the RichTextBox (that I've modified a bit with some additions found here and there) so that when I print, my white text becomes black.
To be more precise, I have a RichTextBox with a PrintDocument, PrintPreviewDialog, and so on. I can print without problem with this setup. The only thing is that my application has a dark theme (it is made to be used mainly by night) and the RichTextBox has a black background and the default text is white.
Therefore, when I print (or preview), the white text stays white and it can't be seen when printed...
I would then like to know how I would need to modify my components to change the font color from white to black upon printing. I do not care about other colors (they are the assumed choice of the user) that will be printed fine anyway.
Thanks so much for your pointers on this!
Put this code in your print handler,
var selection = myRichTextBox.Selection;
if (!selection.IsEmpty)
richTextBox1.SelectionColor = Color.Black;

how to use a textbox but having an underscore line and blinking cursor?

I've created Windows forms and I'm using the textbox control for input, but I like to use it without border and other layout for textbox etc. I just want to use a underscore line and blinking cursor.
I played with the borderStyle (Fixed3D, None), backcolor=InactiveBorder etc. But I still do net get the underline... like this-> _____________ result like this: This is underline______________
I think Backcolor=InactiveBorder and BorderStyle=None is ok to use, but how to get the underline and blinking cursor?
Requirement:
blinking cursor and underline. (The doesn't blink by default, I just see a vertical line))
To fake this, you could add a label below the text box with the content being _____________________. My preferred solution would be to create a simple custom control that just draws a line.
Doesn't the caret on your system blink by default? It does on my system if the focus is on the text box.
If the caret doesn't blink by default, go to the Windows Control Panel and check your Keyboard Settings there - this is the place where you can adjust the caret blink rate.
For creating a underline for your textbox you can do like this,
First add a panel which is in the height of text box's height + underline's height.
Now add your textbox inside of that panel and set its dock to TOP.
Then set the textbox's border to none.
Now set the backcolor of the panel, according to the color need of underline.
Update:
This is VB code, i hope that you can easily convert it into c#
[ Concept: You just need to set the border for all of your textboxes as none.then In forms paint event track those text boxes and draw a line under it. ]
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles Me.Paint
Using xPen As Pen = New Pen(Color.Blue)
' Here we are using LINQ to filter the controls.
' If you don't want it, you just check all the controls by using typeof
' inside the For Each loop.
For Each xTxtBox In Me.Controls.OfType(Of TextBox)()
e.Graphics.DrawLine(xPen,
xTxtBox.Location.X,
xTxtBox.Location.Y + xTxtBox.Height,
xTxtBox.Location.X + xTxtBox.Width,
xTxtBox.Location.Y + xTxtBox.Height)
Next
End Using
End Sub
Use Masked TextBox and set Focus , e.g. maskedtextbox1.Focus(); <== this is for the blinking cursor and the masked textbox to the underline !
try :
To set logical focus to an input control
FocusManager.SetFocusedElement(this, textboxJack);
To set keyboard focus to an input control
Keyboard.Focus(textboxJill);
and for the masked textbox you can set a mask that will not be changed when you delete the text from it not like the simple textbox :)
Good luck
To do this, I would recommend creating a custom control (which is accomplished in the WinForms world by inheriting from one of the provided control classes). That custom control would then:
Provide its own drawing logic (by overriding OnPaint) in order to draw the underline and skip drawing anything else you don't want to see (e.g., the borders of the control).
Create its own caret when it receives the focus, and destroy that caret when it loses the focus. You'll find all the details on how to do this in my answer here.
You can also configure the blink rate of the caret by calling the SetCaretBlinkTime function. But note that this is not recommended, as it changes the global system setting and therefore affects other applications. It is best to do as Thorsten suggests and modify the setting on your machine if you wish to see something different. You should always respect a user's settings. There's a reason that they (or someone else) set up their system to not blink the caret.
Naturally, you will need to use P/Invoke to call these Win32 API functions related to caret management from a C# application. That shouldn't be too difficult if you know what you're doing. If you need a complete solution, consider setting a bounty on this question to persuade me to write one up for you.
I faced the same issue and built something that works fine:
public class TextBox : System.Windows.Forms.TextBox
{
public TextBox()
{
BorderStyle = BorderStyle.None;
Text = "__________"; //Sometime this doesn't work while creating the control in design mode ; don't know why
}
//protected override void OnFontChanged(EventArgs e)
//{
// base.OnFontChanged(e);
// RefreshHeight();
//}
bool loaded = false;
protected override void OnCreateControl()
{
if(!loaded)
RefreshHeight();
base.OnCreateControl();
}
private void RefreshHeight()
{
loaded = true;
Multiline = true;
Size s = TextRenderer.MeasureText(Text, Font, Size.Empty, TextFormatFlags.TextBoxControl);
MinimumSize = new Size(0, s.Height + 1);
Multiline = false;
}
}
I used bool loaded = false to avoid the app to crash in a loop because of OnCreateControl. TextBox control doesn't have OnLoad event (I'm open to another approach).
OnFontChanged can be uncommented if your app change the font size in run time
MinimumSize = new Size(0, s.Height + 1); I added 1 to avoid any error of MeasureText

Prevent combobox from resizing on font change

I have a combo box that has a list of font families in it. As you can guess I'm making a toolstrip for editing fonts in a rich text box control. The problem is when I change fonts it's resizing my combobox.
scrolling through different fonts causes the combo box to become "jumpy" and some fonts have a huge height which is causing for some hilarious problems.
Exhibit A:
Exhibit B:
Yeh... I'll show the code that I have so far... by the way the combobox is just bound to the font families collection.
void box_SelectedIndexChanged(object sender, EventArgs e)
{
String text = ((Font)box.SelectedItem).Name;
Font font = (Font)box.SelectedItem;
BeginInvoke(new Action(() => box.Text = text));
BeginInvoke(new Action(() => box.Font = font));
}
Anyone have any ideas, if I can't find a solution I can just stop the font from changing and just display the name in the default font.
Using a ToolStripComboBox is the problem here I think. The .NET 2.0 ToolItem classes have a lot of residual, erm, features that never got addressed. WPF sucked the resources away. The tool strip is obviously not handling the resize very well. Nor does it make the rest of the form move down when it gets bigger which is by design.
The canonical font combobox uses owner draw to display the fonts in the dropdown list in their regular style. Without changing the font of the box itself. You really don't want the toolstrip to resize, that's just not a great UI.
The only way I can think of doing it is by creating a custom combobox control and deriving from said control. This will give you access to the variable ownerdraw which gives us a little more flexibility without having to mess around with the ItemHeight property. Hooking into one of the events, which dictate that the value of the control has changed.
You could then have a function like the following to calculate the new layout size:
using (Font font = new Font(this.Font.FontFamily, (float)this.PreviewFontSize))
{
Size textSize;
textSize = TextRenderer.MeasureText("yY", font);
_itemHeight = textSize.Height + 2;
}
I tried all these approaches with little success sadly. However I didn't realize it until today when I looked at how microsoft office implements it. They actually use the same font in the combo box for the selected item no matter what font is selected. So as much as I want to make it more custom I'm just going to use a uniform font for whatever font is shown in the selected index.

Categories