日期:2012-12-13  浏览次数:20517 次

---关于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---