C# UWP - Wrong caret size when there is no text - c#

I have a RichEditBox and want to change the font size of the selection. When I don't select anything, and then change the font size, the caret size doesn't get bigger, until I start typing some characters (spaces don't work). When I delete all of those characters, the caret shrinks again, until I type some characters. Is there any possibility to change the caret size immediately, like in programs like Word?
ITextSelection selection = Editor.Document.Selection;
if(selection != null) {
float fontSize;
try {
fontSize = (float) Convert.ToDouble(fontSizeBox.Text);
} catch(FormatException) {
fontSize = 11;
}
selection.CharacterFormat.Size = fontSize;
}
Editor.Focus(FocusState.Programmatic);

You can do this by a trick using PlaceholderText
<RichEditBox PlaceholderText="Input your text" FontSize="52"/>
Update:
Well, I added some screenshot and did the test.
The caret did shrink a little when enter a new line. And it get bigger when RichEditBox changed from palceholder text to your own text.
This is really interesting.
I think this maybe a bug created by Microsoft.
Default:
The first line
Enter a new line

Related

How does the size get calculated when using GetPreferredSize()?

I'm using label to display the message. I have calculated the size of the label by using GetPreferredSize() method. This method works fine when I didn't do any manipulation in sizing the label. But when, I reduce the width of the label, the text gets clipped. However, if I include a newline(\n) at the end of the text to be displayed, the text which gets clipped in previous case is displayed in the next line.
Here is what I tried.
label1.Text = "Are you sure you wish to cancel? \n You will permanently discard any information you have entered!";
label1.Font = new Font(new FontFamily("Calibri"), 15);
Size textSize = label1.GetPreferredSize(Size.Empty); //Works fine.
label1.Size = textSize;
textSize.Width -= 25;
label1.Size = textSize;// Text is clipped.
label1.Text = "Are you sure you wish to cancel? \n You will permanently discard any information you have entered! \n "; //Works fine again!
Refer to the image,
Label Text
If the method calculates the size of the label based on the contents, why does the content clipped in case2 and works good in case3? How does the width and height is related to? Can anyone explain what I'm missing?
Thanks,
Sindhu
Size sz = new Size(this.Width, Int32.MaxValue);
sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
this.Height = sz.Height;
where "this " is your control.
How big was text size before decreasing it by 25? Maybe it's just not enough space and cut off - try with a different number. And ... you certainly wanted to subtract and not assign?
Modify the "Anchor" setting to only anchor to the left or the right

Compress text to fit within a control's displayed width

In my C# WinForms application, I have a control in which I display some text to the user on screen. For time being, assume it is a TextBox.
My requirement is if the text does not fully fit within the displayed width of the control, I want to keep reducing the font size or compress the text in some other way to fit the displayed width of the control.
I understand in extreme situations, the text may not be readable at all. But that's fine.
Can I get a code example how to achieve this?
To measure the width of the font you'll have to determine it using TextRenderer. The following code illustrates how to achieve this, and to resize the font in the textbox.
var text = "Some unnecessarily long, long, long string.";
var size = default(SizeF);
// SizeF size; // Use this if you're on an older version of C# without default
do
{
using (var font = new Font(textBox1.Font.Name, textBox1.Font.SizeInPoints))
{
size = TextRenderer.MeasureText(text, font);
if (size.Width <= textBox1.Width)
textBox1.Text = text;
else
{
textBox1.Text = "Won't fit";
textBox1.Font = new Font(font.Name, font.SizeInPoints - 1f);
}
}
} while (size.Width > textBox1.Width);
You may want to adjust the by how much the font size decreases if it ends up too small for your liking.

Bug in RichTextBox font color when appending Null character

I have an application (developed in C#, .Net 2.0, VS 2010 SP1) that reads/writes to the serial port and and puts the communication on a RichTextBox control. I have been asked to color code the contents based on the direction (whether they are incoming or outgoing) and mark where there are control characters (kind of similar to RealTerm when they show which control character is in the message). therefore in a method when there is a control character I add <> tag. when I want to update my RTF using the string from the aforementioned method, I look for '<' and '>' and change the color of the text. However, if the character to be added is 0x00 or null after tag, when I call the .append method of RTB, the fontcolor switches to what it was before and therefore the string after gets the same color as the tag.
I have already found a work around for this issue by changing the color after the append method but this seemed very curious to me. I reviewed many online discussions/questions on this website and MSDN but nobody has addressed this and read RichTextbox documentation. Am I missing something obvious? Or is this just another VS issue?
this is the method that determines the color and appends the characters to the RTB:
private void FormatAndAddText(string text_, bool isRx_)
{
RichTextBox.DeselectAll(); //If I dont call this method, If the user has selected the some text, the starred line will change the font color of the selection
Color mainTextColor = (isRx_ ? Color.LawnGreen : Color.Yellow);
Color tagsTextColor = (isRx_ ? Color.Red : Color.Blue);
RichTextBox.SelectionColor = mainTextColor; //****this will modify the color of the text, if user has selected some of it.
for(int i = 0; i< text_.Length; i++)
{
char char = text_[i];
if (_char == '<')
RichTextBox.SelectionColor = tagsTextColor ;
RichTextBox.AppendText(char.ToString()); //if char is 0x00, the color resets!!!
if ((i < text_.Length-1))
{
if (char == '>')
RichTextBox.SelectionColor = mainTextColor; //change the color to what it is supposed to be.
}
}
}

TextBox.Text Doesn't Right Justify

According to my understanding, the code below should right-justify the text if the text is longer than the textbox can show, otherwise it keeps it left-justified.
The problem is that it doesn't actually do this and it's acting really odd. Short strings end up right-justified sometimes and long strings are always left-justified.
What am I doing wrong?
private void textBoxCurrentConfig_TextChanged(object sender, EventArgs e)
{
SizeF stringSize = new SizeF();
stringSize = TextRenderer.MeasureText(textBoxCurrentConfig.Text, textBoxCurrentConfig.Font);
float currentTextWidth = stringSize.Width;
float allowedTextWidth = textBoxCurrentConfig.Size.Width - 10;
if (currentTextWidth >= allowedTextWidth) // if the text we want to display is larger than the textbox can hold, right justify it to show the filename
{
textBoxCurrentConfig.TextAlign = HorizontalAlignment.Right; // right justify
}
else // otherwise we can display the entire path
{
textBoxCurrentConfig.TextAlign = HorizontalAlignment.Left; // left justify
}
textBoxCurrentConfig.Refresh();
this.Refresh();
}
As from your comments, you want to move cursor position according to the text length. You can use TextBox.Select() method for this. Check MSDN for details.
So if you want to move cursor at the the start of text, you can use
textBoxCurrentConfig.Select(0, 0);
and if you want to move cursor at the end of text, you can use
textBoxCurrentConfig.Select(textBoxCurrentConfig.Text.Length, 0);
Try to remove
this.Refresh();
It's may cause the page to refresh and return the text box to the original align

Label with an Image on the left - preventing the text to come over the picture?

I want to report status of an operation in a WinForm application written in C#.
To make it more user-friendly, I want to show an icon on the left depending on the status.
Animated GIF during the process
Ok or Error icon depending on the result.
I wanted to use the native WinForms Label control which works well with animated GIFs and looks as standard as it can get.
My problem however is that text comes is written over the picture.
There does not seem to be any property to set a margin for the text.
I tried the most obvious thing, which is to prefix it with spaces, which works, except when the text wraps to the next line, as shown below.
I would prefer not spend too much time writing/testing/debugging derived control for this if possible...
I could put a quick and dirty user-control, with a picturebox on the left of a label, but it doesn't feel very clean.
Is there any trick to get around this quickly and elegantly, or can someone point me to a Label derived class supporting this that is relatively lightweight? (I had a look at CodeProject but couldn't find much).
Thank you.
A simple alternative is to use a Button instead of a Label, as shown below:
By using the following properties, you can style the Button to look just like a Label, whilst also having the option to keep the image and text aligned next to eachother:
FlatAppearance ↴
BorderSize = 0
MouseDownBackColor = Control
MouseOverBackColor = Control
FlatStyle = Flat
Image = [Your image]
ImageAlign = MiddleLeft
Text = [Your text]
TextAlign = MiddleLeft
TextImageRelation = ImageBeforeText
A simple way to achieve the desired effect; no user controls!
The quick-and-dirty usercontrol with an image and a separate label is your best option. Just add a public string property to set the label's text and you're pretty much done.
Here's a different solution that I find less hacky than the "styled button" approach. It also allows you to set the distance (spacing) between the image and the text.
class ImageLabel : Label
{
public ImageLabel()
{
ImageAlign = ContentAlignment.MiddleLeft;
}
private Image _image;
public new Image Image
{
get { return _image; }
set
{
const int spacing = 4;
if (_image != null)
Padding = new Padding(Padding.Left - spacing - _image.Width, Padding.Top, Padding.Right, Padding.Bottom);
if (value != null)
Padding = new Padding(Padding.Left + spacing + value.Width, Padding.Top, Padding.Right, Padding.Bottom);
_image = value;
}
}
protected override void OnPaint(PaintEventArgs e)
{
if (Image != null)
{
Rectangle r = CalcImageRenderBounds(Image, ClientRectangle, ImageAlign);
e.Graphics.DrawImage(Image, r);
}
base.OnPaint(e); // Paint text
}
}
One alternative to a UserControl would be to use a TableLayoutPanel with two columns and one row, placing the image control in one cell and the text control in the other.
Its an old question, but maybe someone will look here just like I got here...
You can use the Align on the Image and on the text:
label.TextAlign = ContentAlignment.MiddleRight;
label.ImageAlign = ContentAlignment.MiddleLeft;
nameoftextlabel.hidden=1
That should work.

Categories