Yes, you'll get unexpected behavior if you set the RightToLeft
property anywhere other than a control's constructor (in VB.NET parlance, that's the New
method).
In fact, the constructor is where you should set all of the properties of a form or control object. If you come from VB 6, it might seem logical to do it in the Load
event handler, but that's not idiomatic .NET and, as you've discovered, can cause problems when initializing certain properties.
The technical reason for this is that certain properties (like RightToLeft
) can actually only be set on the native window (which is how the Form
objects used in the .NET world are implemented behind the scenes) at the time that it is created. When you attempt to change the property, the framework code actually has to destroy and then re-create the native window with the new property values.
Change the code to look like this instead:
Public Class Form1
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
modControls.SetFormRtl(Me)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.Hide()
Dim f As New Form2
f.ShowDialog()
MessageBox.Show("After dialog closed.")
End Sub
End Class
Public Class Form2
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
modControls.SetFormRtl(Me)
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class
Speaking of non-idiomatic .NET code:
Methods should all be Pascal cased by convention. That means your
setFormRTL
method should be namedSetFormRtl
.A helper function that sets the properties of an object just seems wrong to me. If anything, that's just bad OO design. If you want this method to be available for all of your
Form
objects, derive a custom form class and add this method (or even do the desired initialization in the constructor). Either way, all forms that you derive from this custom form object will inherit the functionality. Example:Public Class MyCustomForm : Inherits System.Windows.Forms.Form Public Sub New() MyBase.New() Me.SetRtl() End Sub Public Sub SetRtl() Me.RightToLeft = RightToLeft.Yes End Sub End Class Public Class Form1 : Inherits MyCustomForm Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load Me.Hide() Dim f As New Form2 f.ShowDialog() MessageBox.Show("After dialog closed.") End Sub End Class Public Class Form2 : Inherits MyCustomForm Private Sub Form2_Load(sender As Object, e As EventArgs) Handles Me.Load End Sub End Class