1

I have an extended RichTextBox:

public class RichTextBoxEx : RichTextBox
{
    protected override void OnCreateControl()
    {
        Text = "Hello World";
        base.OnCreateControl();
    }
}

When I remove the border using BorderStyle = BorderStyle.None;, the method is called twice:

protected override void OnCreateControl()
{
    BorderStyle = BorderStyle.None;
    Text = "Hello World";
    base.OnCreateControl();
}

Why is this happening?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Michael Haddad
  • 4,085
  • 7
  • 42
  • 82
  • WinForms is like that, particularly at the point where a control is halfway through being created. WinForms lets you style a control both before and after window creation time using behind-the-scenes magic (many _styles_ can only be applied right as the control is created in Win32 -WinForms will tear down and recreate a window (if it needs to) to get this done) If this behavior gets in the way, use a static Boolean to prevent long-executing code from running twice, otherwise, just be happy you don't have to write the Win32 code that you get from Windows Forms for free. – Flydog57 Feb 11 '19 at 20:24
  • Or... Try setting the style before `OnCreateControl`. That way, the control will be created with the style you want, without having to create, tear-down and recreate the control – Flydog57 Feb 11 '19 at 20:27
  • @Flydog57 - When I edit the `Margin` property, it works just fine. So what is the difference between `Margin` and `BorderStyle`? – Michael Haddad Feb 11 '19 at 20:28
  • If you are programming directly in Windows (using Win32 and friends (this is actually User32)), windows (WinForms controls are usually windows) have properties, styles and extended styles. Styles and extended styles are set when the window is created. Properties (like "Text", "Foreground Color", etc.) can be set at any time. If the actual window has been created (the Windows.Forms.Control instance has a Handle associated with it) and you change something that's a style or extended style, Windows Forms destroys the existing control and recreates one in its place. Uh - Just Because. – Flydog57 Feb 11 '19 at 20:34
  • Some of this is explained here: https://blogs.msdn.microsoft.com/jfoscoding/2004/11/24/all-about-handles-in-windows-forms/. Look for "recreate" – Flydog57 Feb 11 '19 at 20:42

1 Answers1

1

When setting BorderStyle, it checks if the new border style is different from the current value, it recreates the handle which result in a call to OnCreateControl at the end of method calls.

If you want to change the default value for BorderStyle property which has been set in TextBoxBase control, the correct location is in constructor of your control:

public class RichTextBoxEx : RichTextBox
{
    RichTextBoxEx ()
    {
        BorderStyle = BorderStyle.None;
    }
}

The Text property is different. I've described about it an answer to your other question.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398