[VB.NET]浅谈MDI窗体的多窗体编程2

类别:.NET开发 点击:0 评论:0 推荐:

---关于WITH结构内的MDI窗体实例--

在上一篇内,介绍了MDI窗体的实例

http://blog.csdn.net/allenle/archive/2005/02/18/293122.aspx

在第二段代码中写到


    Private Shared fr As New frmName
    Private Sub ToolBar1_ButtonClick()Sub ToolBar1_ButtonClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolBarButtonClickEventArgs) Handles ToolBar1.ButtonClick
        Select Case e.Button.Text
            Case "OK"  '"OK" is ToolBarButton.Text
                If fr Is Nothing Or fr.IsDisposed Then
                    fr = New frmName
                    fr.MdiParent = Me
                    fr.Show()
                Else
                    fr.MdiParent = Me
                    fr.Show()
                    fr.Focus()
                End If
        End Select
    End Sub

今天又调试了一下,使用了WITH结构,代码如下

    Private Shared fr As New frmName
    Private Sub ToolBar1_ButtonClick()Sub ToolBar1_ButtonClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolBarButtonClickEventArgs) Handles ToolBar1.ButtonClick
        Select Case e.Button.Text
            Case "OK"  '"OK" is ToolBarButton.Text
                With fr
                    If fr Is Nothing Or fr.IsDisposed Then
                        fr = New frmName
                        .MdiParent = Me
                        .Show()
                    Else
                        .MdiParent = Me
                        .Show()
                        .Focus()
                    End If
                End With
        End Select
    End Sub


调试出现一错误:Cannot access a disposed object named "frmName".

想了一下,修改了代码,如下
就是把with的范围缩小到fr实例化之后,调试成功~
    Private Shared fr As New frmName
    Private Sub ToolBar1_ButtonClick()Sub ToolBar1_ButtonClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolBarButtonClickEventArgs) Handles ToolBar1.ButtonClick
        Select Case e.Button.Text
            Case "OK"  '"OK" is ToolBarButton.Text
                If fr Is Nothing Or fr.IsDisposed Then
                    fr = New frmName
                    With fr
                        .MdiParent = Me
                        .Show()
                    End With
                Else
                    With fr
                        .MdiParent = Me
                        .Show()
                        .Focus()
                    End With
                End If
        End Select
    End Sub
所以大家使用的时候要当心点
分析,就是关闭了实例了一次的窗口后,fr is nothing ,所以fr是不被with所使用的,改了with的使用范围之后就没有错误出现.
---end---

本文地址:http://com.8s8s.com/it/it41773.htm