Creating new Forms with the same properties

Joined
Jun 9, 2013
Messages
13
Programming Experience
1-3
Basically all I'm trying to do is create multiple forms with the same properties. By properties, I mean that they are the same size, are unable to maximize and all that delicious property stuff.

I can simple create a new Form and manually change the properties, but this seems to me as to much hard work.
 
Design your form the way you want it and then simply create multiple instances of it. If you want to create multiple instances with properties other than the defaults then you could declare a constructor that had parameters for all the properties of interest and pass the same values each time. Alternatively, you can implement ICloneable and have your Clone method create a new instance with all the same property values as the existing instance.
 
Question: I used this code

Public Class Intro
Dim shwForm As New Form1
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
shwForm.Show()
End Sub
End Class

When I click the button twice the program crashes. I thought that by using the New keyword a new instance of form one will run.
 
I thought that by using the New keyword a new instance of form one will run.
That variable is only initialized once. When the form is closed that variable will refer to a disposed object.
 
Question: I used this code

Public Class Intro
Dim shwForm As New Form1
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
shwForm.Show()
End Sub
End Class

When I click the button twice the program crashes. I thought that by using the New keyword a new instance of form one will run.

Unless you need to refer to it in some other method(s), the variable should be inside the event handler. If you do need to refer to it elsewhere then it must be outside but you still need to use the New keyword inside. You want to create a new form each time you click the Button so the New keyword needs to be inside the Click event handler.
 
Yea, I figure that out about 2 minutes after and had a complete Eureeka moment.

I'm still struggling with this subject of creating multiple forms with the same properties, I'll try to explain in more depth.

I'm wanting multiple forms of the same size, same font, unable to maximize, unable to resize borders.
I created the multiple forms, 11 all together, and thought that there must be an easier way than resizing all of them.

Could you explain in a tutorial type of way...

(And if not, how do I create this constructor)


**UPDATE**

Would it be good programming to just create a class with a method in with the parameters and then call that class into each form when it loads?
 
What do you not understand about the information you found about constructors when you searched the web? If you didn't understand something then that's fine. If you didn't try to find information for yourself, that's not fine.

By the way, your form is a class and a constructor is a method.
 
Ok, well am having trouble, I think I need to go back and study more, am not a complete noob but a noob I am, I don't suppose you can suggest me some great books to get.
 
What you want to do is very easily achieved through inheritance:

Public Class ModelForm
    Inherits Form

    Private Sub MyForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Set your default properties here
        Me.BackColor = Color.Black

    End Sub

End Class

Public Class Form1
    ' Add this line to every form you want to create from your model.
    Inherits ModelForm

End Class


What we do here is create a subclass of the Form class, set all its default properties as you wish, then have all other forms inherits from it.
 
Here is a complete example that I wrote a little while ago, for a real-time game combat log parser. I needed a small, always on top, autosizing, semi transparent form that could be switched between two modes with a hotkey (either opaque and moveable, or transparent, clickthrough, and unmovable). That form needed a custom title bar with just a close button and title, and a preconfigured listview.

It's a bit more involved and serves a specific purpose, but it's a good real-world example I think:

Imports System.Runtime.InteropServices

Public Class TransparentNotify
    Inherits Form

    ' Win32 API imports.
    <DllImport("user32", EntryPoint:="GetWindowLong")> _
    Private Shared Function GetWindowLong(ByVal hWnd As IntPtr, ByVal nIndex As GWL) As Integer
    End Function
    <DllImport("user32", EntryPoint:="SetWindowLong")> _
    Private Shared Function SetWindowLong(ByVal hWnd As IntPtr, ByVal nIndex As GWL, ByVal dsNewLong As TransparentNotify.WinStyles) As Integer
    End Function
    <DllImport("user32.dll", EntryPoint:="SetLayeredWindowAttributes")> _
    Private Shared Function SetLayeredWindowAttributes(ByVal hWnd As IntPtr, ByVal crKey As Integer, ByVal alpha As Byte, ByVal dwFlags As LWA) As Boolean
    End Function
    <DllImport("user32.dll", SetLastError:=True)> _
    Private Shared Function RegisterHotKey(ByVal hWnd As IntPtr, ByVal id As Integer, ByVal fsModifiers As UInteger, ByVal vk As UInteger) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function
    <DllImport("user32.dll", SetLastError:=True)> _
    Private Shared Function UnregisterHotKey(ByVal hwnd As IntPtr, ByVal id As Integer) As Integer
    End Function
    <DllImport("user32.dll")> _
    Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
    End Function
    <DllImport("user32.dll")> _
    Private Shared Function ReleaseCapture() As Boolean
    End Function

    ' Override CreateParams to enable form drop shadow.
    Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
        Get
            Const CS_DROPSHADOW = &H20000
            Dim cp As CreateParams = MyBase.CreateParams

            cp.ClassStyle = cp.ClassStyle Or CS_DROPSHADOW
            Return cp
        End Get
    End Property

    ' Private constant enums.
    Private Enum GWL As Integer
        ExStyle = -20
    End Enum
    Private Enum LWA As Integer
        ColorKey = &H1
        Alpha = &H2
    End Enum

    Private Const WM_HOTKEY = 786
    Private Const WM_NCLBUTTONDOWN = 161
    Private Const HTCAPTION = 2

    Private intFormInitialStyle As Integer
    Private decFormAlpha As Decimal
    Private intExtendedWinStyle As Integer
    Private boolFormTransparencyToggle As Boolean = False
    Private boolEnableHotkey As Boolean = False

    Private HotkeyMod As Hotkeys
    Private HotkeyMain As Keys

    ' Public constant enums.
    Public Enum WinStyles As Integer
        TRANSPARENT = &H20
        LAYERED = &H80000
    End Enum
    Public Enum Hotkeys As Integer
        MOD_NONE = 0
        MOD_ALT = 1
        MOD_CONTROL = 2
        MOD_SHIFT = 4
        MOD_WIN = 8
    End Enum

    Public Property TN_HotkeyModifier As Hotkeys
        Get
            Return HotkeyMod
        End Get
        Set(value As Hotkeys)
            HotkeyMod = value
        End Set
    End Property
    Public Property TN_HotkeyMainKey As Keys
        Get
            Return HotkeyMain
        End Get
        Set(value As Keys)
            HotkeyMain = value
        End Set
    End Property
    Public Property TN_EnableHotkey As Boolean
        Get
            Return boolEnableHotkey
        End Get
        Set(value As Boolean)
            boolEnableHotkey = value
            Try
                If boolEnableHotkey = True Then
                    RegisterHotKey(MyClass.Handle, 1, HotkeyMod, CUInt(HotkeyMain))
                Else
                    UnregisterHotKey(MyClass.Handle, 1)
                End If
            Catch ex As Exception
                boolEnableHotkey = False
                MessageBox.Show(ex.Message, Me.Name, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Set
    End Property
    Public Property TN_IsTransparentToClicks As Boolean
        Get
            Return boolFormTransparencyToggle
        End Get
        Set(value As Boolean)
            boolFormTransparencyToggle = value
            Try
                If boolFormTransparencyToggle = False Then
                    SetWindowLong(MyBase.Handle, GWL.ExStyle, intFormInitialStyle Or WinStyles.LAYERED)
                Else
                    SetWindowLong(MyBase.Handle, GWL.ExStyle, intFormInitialStyle Or WinStyles.LAYERED Or WinStyles.TRANSPARENT)
                End If
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End Set
    End Property

    Private Components As System.ComponentModel.IContainer

    Friend WithEvents TitleText As System.Windows.Forms.Label
    Friend WithEvents ResultsListView As DBListView
    Friend WithEvents Ability As System.Windows.Forms.ColumnHeader
    Friend WithEvents Damage As System.Windows.Forms.ColumnHeader
    Friend WithEvents Percent As System.Windows.Forms.ColumnHeader
    Friend WithEvents CloseButton As System.Windows.Forms.Label

    Public Event HotkeyPressed()

    Public Sub New(Name As String, Text As String, BackColor As Color, ClientSize As Size)
        InitializeComponent(Name, Text, BackColor, ClientSize)
        intFormInitialStyle = GetWindowLong(Me.Handle, GWL.ExStyle)
    End Sub

    Public Sub DoLayout(ByRef FightData As System.Data.DataView)
        With ResultsListView
            .Items.Clear()
            .Groups.Clear()

            .Groups.Add("Total", "Total")
            For Each Row As System.Data.DataRowView In FightData
                Try
                    If Not .Groups.Item(Row.Item("Group")).Header = Row.Item("Group") Then
                    End If
                Catch ex As Exception
                    .Groups.Add(Row.Item("Group"), Row.Item("Group"))
                End Try
                Dim ListViewItem As New ListViewItem With {.Group = ResultsListView.Groups.Item(Row.Item("Group")), .Text = Row.Item("AbilityText")}
                ListViewItem.SubItems.Add(Row.Item("Amount"))
                ListViewItem.SubItems.Add(Row.Item("PerSecond"))
                .Items.Add(ListViewItem)
            Next
            .Size = New System.Drawing.Size(.Size.Width, (.Items.Count * 17.25) + (.Groups.Count * 22.75) + 5)
            Me.TopMost = True
        End With
    End Sub

    ' Reference template designer.
    Private Sub InitializeComponent(Name As String, Text As String, BackColor As Color, ClientSize As Size)
        With Me
            .SuspendLayout()

            .TitleText = New System.Windows.Forms.Label()
            .CloseButton = New System.Windows.Forms.Label()
            .ResultsListView = New DBListView()
            .Ability = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
            .Damage = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
            .Percent = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)

            .DoubleBuffered = True
            .AutoSize = True
            .MaximizeBox = False
            .AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 14.0!)
            .AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
            .AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
            .AutoValidate = System.Windows.Forms.AutoValidate.EnablePreventFocusChange
            .FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
            .ShowInTaskbar = False

            .Font = New System.Drawing.Font("Tahoma", 7.75!, FontStyle.Regular, GraphicsUnit.Point, CType(0, Byte))
            .BackColor = BackColor
            .ClientSize = ClientSize
            .Name = Name
            .Text = Text

            With TitleText
                .Name = "lblTitle"
                .BackColor = BackColor
                .ForeColor = Me.ForeColor
                .Font = New System.Drawing.Font("Tahoma", 7.75!, FontStyle.Bold, GraphicsUnit.Point, CType(0, Byte))
                .AutoSize = False
                .Size = New Size(Me.ClientSize.Width - 15, 16)
                .Location = New System.Drawing.Point(0, 0)
                .Text = Text
                .TextAlign = ContentAlignment.MiddleLeft
                .Margin = New System.Windows.Forms.Padding(0)
                .BorderStyle = BorderStyle.FixedSingle
            End With

            With CloseButton
                .Name = "btnClose"
                .BackColor = Color.IndianRed
                .ForeColor = Me.ForeColor
                .Font = New System.Drawing.Font("Tahoma", 7.75!, FontStyle.Bold, GraphicsUnit.Point, CType(0, Byte))
                .AutoSize = False
                .Size = New Size(16, 16)
                .Location = New System.Drawing.Point(TitleText.Width - 1, 0)
                .Text = "X"
                .TextAlign = ContentAlignment.MiddleCenter
                .Margin = New System.Windows.Forms.Padding(0)
                .BorderStyle = BorderStyle.FixedSingle
            End With

            With .Ability
                .Text = "Ability"
                .TextAlign = System.Windows.Forms.HorizontalAlignment.Left
                .Width = CInt(Me.ClientSize.Width * 0.46)
            End With

            With .Damage
                .Text = "Damage"
                .TextAlign = System.Windows.Forms.HorizontalAlignment.Right
                .Width = CInt(Me.ClientSize.Width * 0.27)
            End With

            With .Percent
                .Text = "Percent"
                .TextAlign = System.Windows.Forms.HorizontalAlignment.Right
                .Width = CInt(Me.ClientSize.Width * 0.27)
            End With

            With .ResultsListView
                .BackColor = Me.BackColor
                .BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
                .Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.Ability, Me.Damage, Me.Percent})
                .Font = Me.Font
                .FullRowSelect = True
                .HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None
                .LabelWrap = False
                .Location = New System.Drawing.Point(0, 15)
                .Margin = New System.Windows.Forms.Padding(0)
                .MultiSelect = False
                .Name = "ResultsListView"
                .Scrollable = False
                .Size = Me.ClientSize
                .TabIndex = 0
                .UseCompatibleStateImageBehavior = False
                .View = System.Windows.Forms.View.Details
            End With

            .Controls.Add(.ResultsListView)
            .Controls.Add(.TitleText)
            .Controls.Add(.CloseButton)
            .TopMost = True
            .ResumeLayout(False)

        End With
    End Sub

    ' Override WindowProc to intercept our hotkey and raise an external event to signal client application.
    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = WM_HOTKEY Then
            If m.WParam.ToInt64() = 1 Then
                RaiseEvent HotkeyPressed()
            End If
        End If
        MyBase.WndProc(m)
    End Sub

    ' Window is movable while not transparent by dragging from any of its control's client area.
    Private Sub TransparentNotify_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
        ReleaseCapture()
        SendMessage(Me.Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0)
    End Sub
    Private Sub ResultsListView_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ResultsListView.MouseDown
        ReleaseCapture()
        SendMessage(Me.Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0)
    End Sub
    Private Sub TitleText_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles TitleText.MouseDown
        ReleaseCapture()
        SendMessage(Me.Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0)
    End Sub

    ' Close button hides the window.
    Private Sub CloseButton_Click(sender As Object, e As System.EventArgs) Handles CloseButton.Click
        Me.Visible = False
    End Sub

    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso Components IsNot Nothing Then
                Components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

End Class


' Double buffered 100% flicker free listview.
Friend Class DBListView
    Inherits System.Windows.Forms.ListView

    Public Sub New()
        Me.SetStyle(ControlStyles.OptimizedDoubleBuffer Or ControlStyles.AllPaintingInWmPaint, True)
        Me.SetStyle(ControlStyles.EnableNotifyMessage, True)
    End Sub

    Protected Overrides Sub OnNotifyMessage(m As System.Windows.Forms.Message)
        If Not m.Msg = &H14 Then
            MyBase.OnNotifyMessage(m)
        End If
    End Sub
End Class
 
Ok, now that I have created the form to the specification I want each form to have, I now need to drop objects such as buttons etc. How do I create these through code.
 
Back
Top