Karlton
Karlton

Reputation: 35

How to execute code in design mode for winforms

I WANT to execute code when I open a winform in the designer. In particular, I want the designer to automatically size the working form to a percentage of my screen. similar to this:

pForm.Size = New Drawing.Size(MyScreen.WorkingArea.Width * 0.75, MyScreen.WorkingArea.Height * 0.75)

There's got to be a way besides manually modifying the initializecomponant routine ... which would be a bad idea anyway and I don't want to set the size property in every blessed form to a static value

Thanks for any assistance (VB.NET)

Upvotes: 2

Views: 929

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

As an option to run the code in design mode of a form, you can put the code in base class of the form.

The code which you put in the base class of a form will run in design mode of the inherited form. So if you would like to run a code in design mode of a form, you can create a base form and inherit from that form. Then put your code in the methods of the base form.

Example

  1. Add New Item and choose a Form and set the name to MyBaseForm.
  2. Paste the following code in MyBaseForm.vb:

    Imports System.ComponentModel
    Public Class MyBaseForm
        Protected Overrides Sub OnSizeChanged(e As EventArgs)
            If DesignMode Then
                Dim s = New Size(My.Computer.Screen.WorkingArea.Width * 0.75,
                                 My.Computer.Screen.WorkingArea.Height * 0.75)
                TypeDescriptor.GetProperties(Me)("Size").SetValue(Me, s)
            End If
            MyBase.OnSizeChanged(e)
        End Sub
    End Class
    
  3. Build the project.
  4. Add New Item and choose a InheritedForm and choose MyBaseForm as the base form.

Upvotes: 2

Related Questions