I am trying to use the SetTextJustification function, but it does not work as expected.
If I set the argument value of nBreakExtra to 40 or to 10 the output is the same, why is this?
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
IntPtr hdc = richTextBox1.CreateGraphics().GetHdc();
string str = "aaa bbb ccc ddd eee fff";
SetTextJustification(hdc, 40, 5);
TextOut(hdc, 20, 20, str, str.Length);
SetTextJustification(hdc, 10, 5);
TextOut(hdc, 20, 50, str, str.Length);
}
[DllImport("gdi32.dll")]
static extern bool SetTextJustification(IntPtr hdc, int nBreakExtra, int nBreakCount);
[DllImport("gdi32.dll", CharSet = CharSet.Auto)]
static extern bool TextOut(IntPtr hdc, int nXStart, int nYStart, string lpString, int cbString);
the output is displayed as:

Your code seems to work ok. Here is a screen shot of my test:
I am not sure why your results are different.
Perhaps I could offer this as an alternative solution:
I have writen my own justification method:
Using this new method lets you choose the font and specify the total length of the line, it also allows you greater flexibility and customization (e.g. incoporating a flag that indicates if the last line should be justified or not). You could also customize the method further by including the font color as a method argument.
This method can now be used as shown in the button event method below (note the first bit of this event handler method includes the code for testing the origonal solution):
Here is a screen shot of the results that show both approaches:
Anyway I hope this helps.