Click here to Skip to main content
14,208,035 members
Rate this:
 
Please Sign up or sign in to vote.
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:

if (fontDialog1.ShowDialog() == DialogResult.OK & !String.IsNullOrEmpty(rtbText.Text))
{
                
  rtbText.SelectionFont = fontDialog1.Font;
}
Posted
Updated 14-Aug-17 3:51am
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

You can select all the text before changing SelectedFont:
rtbText.SelectAll();
rtbText.SelectionFont = fontDialog1.Font;
   
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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;
        }
    }
}
   
v2
Comments
Member 9314342 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
Member 9314342 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)



Advertise | Privacy | Cookies | Terms of Service
Web03 | 2.8.190612.1 | Last Updated 14 Aug 2017
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100