Monday 28 September 2009

VB MDI

VB MDI

MDI stands for Multiple Document Interface. An MDI application is an application in which you can view and manipulate several documents at the same time. A good example of an MDI application used the world over is Microsoft Excel.

Visual Basic.Net allows the developer to create MDI applications as well as SDI applications, here is a quick overview of VB MDI.

To create an MDI application open a new Windows Application in Visual Basic.NET. As usual the new application will open with a default form name Form1.

*To keep things simple we will not bother renaming forms and controls.*


Add another form, (unsurprisingly Form2) to this application by right-clicking on the project name in the Solution Explorer window and selecting Add->Add Windows Form.

If you want you can place some controls on Form2.

For this example we will set Form1 as the MDI parent window and Form2 as MDI child window.

*MDI child forms are important for MDI apps as users interact mostly through the child forms.*

Select Form1 and set (in the Windows Style section) the property IsMdiContainer to True.

By setting it to true it designates this form as an MDI 'Container' for the child windows. Once that property has been set to True you will notice that the form has changed colour.

Drag any Main Menu component from the toolbox onto Form1. Child windows will show when a menu item is clicked. Name the top-level menu item 'File' and submenu items as 'New Child Window', 'Arrange Child Forms' and 'Close'.

Now you need to add some code:

*Note that we still use hungarian notation when declaring variables.*

m prefix denotes it is a 'member' of the current module
i prefix denotes an integer variable

Go into code view of the form. Right at the top of the form you will see:

Public Class Form1 Inherits System.Windows.Forms.Form

Add in:

'---------- Member Variables ----------
Dim miChildForm As Integer = 0
Dim mChildForms(5) As Form2 'Array to store child windows

'---------- Member Procedures ---------
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
End Sub

Private Sub MenuItem2_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles MenuItem2.Click
miChildForm += 1 'Same as miChildForm = miChildForm + 1
mChildForms(miChildForm) = New Form2()
mChildForms(miChildForm).Text = "Child Form: " & Str(miChildForm)

'Set title for child windows and increment the number with an array
mChildForms(miChildForm).MdiParent = Me
mChildForms(miChildForm).Show()
End Sub

Private Sub MenuItem3_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles MenuItem3.Click
Me.LayoutMdi(MdiLayout.Cascade)

End Sub

Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal_
e As System.EventArgs) Handles MenuItem4.Click
Me.Close()
End Sub

Hit F5 to run the app and have a play!
Nice and easy code to get you going with VB MDI

No comments:

Post a Comment