Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm working on a text editor and the one button i use is to change the font type and size of all the text in in a richtextbox and if you select something only that text should change with the fontDialog..The code i have at the moment i can select text and change the selected text's style and then continue typing with the original font type i started with..i just need help with the code i can you use to change all the text if nothing is selected/higlighted

What I have tried:

C#
if (fontDialog1.ShowDialog() == DialogResult.OK & !String.IsNullOrEmpty(rtbText.Text))
{
                
  rtbText.SelectionFont = fontDialog1.Font;
}
Posted
Updated 14-Aug-17 3:51am
v2

You can select all the text before changing SelectedFont:
rtbText.SelectAll();
rtbText.SelectionFont = fontDialog1.Font;
 
Share this answer
 
I've used this in the past; it handles the case of all-selected in the same way as none-selected. And, you can, optionally, reset the selection after the Font change.
private void SetFont(RichTextBox rtbx, bool restoreselection = false)
{
    int selStart = rtbx.SelectionStart;
    int selLength = rtbx.SelectionLength;

    if (fontDialog1.ShowDialog() == DialogResult.OK)
    {
        if (selLength == 0) rtbx.SelectAll();

        rtbx.SelectionFont = fontDialog1.Font;

        if (restoreselection)
        {
            rtbx.Focus();
            rtbx.SelectionStart = selStart;
            rtbx.SelectionLength = selLength;
        }
    }
}
 
Share this answer
 
v2
Comments
DreyerVorster 15-Aug-17 3:24am    
how do i use or implement the SetFont?
BillWoodruff 15-Aug-17 3:45am    
'SetFont is a Method: you call it by passing it a reference to a RichTextBox, and an optional boolean parameter that will control whether the delection is restored:

SetFont(myRichTextBox); // selection not restored

SetFont(myRichTextBox, true); // selection restored
DreyerVorster 15-Aug-17 3:52am    
Thank you so so much
Karthik_Mahalingam 16-Aug-17 3:20am    
5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900