由于以前用VB6.0做过系统,编辑的时候第一个想的是unload方法,但是实际不是这样的,VB.net 中根本就没有unload方法,但是看到了frmclosing方法,接着我就写了程序:
Private Sub Frmmain_FormClosing(ByVal sender As Object,ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing If MsgBox("你真的要退出吗?",vbOKCancel,"提示") = vbCancel Then e.Cancel = True Else Dim BOffwork As New BllOffwork Dim EOnwork As New Onwork Dim EWorkRecord As New WorkRecord Dim strUserName As String = FrmLogin.strUserName Try EOnwork = BOffwork.InquireOnwork(strUserName) EWorkRecord.EUserName = strUserName EWorkRecord.EOnworkTime = EOnwork.EOnworkTime EWorkRecord.EOffworkTime = Now BOffwork.Offwork(strUserName,EWorkRecord) Me.Close() Catch ex As Exception MsgBox(ex.Message) End Try End If End Sub
结果发现:如果选择不退出,程序要执行两遍,弹出两次“询问是否退出”的窗口,如果选择确定退出,会一直弹出“询问是否退出”窗口。调试了一下发现me.close()导致程序再次执行,但是如果删掉的话,整个程序就不能退出,以至成为死循环。
后来查了一下资料,知道了窗口的关闭有两个方法:formclosing() formclosed() 遂改动如下:
Private Sub Frmmain_FormClosed(ByVal sender As Object,ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed Dim BOffwork As New BllOffwork Dim EOnwork As New Onwork Dim EWorkRecord As New WorkRecord Dim strUserName As String = FrmLogin.strUserName Try EOnwork = BOffwork.InquireOnwork(strUserName) EWorkRecord.EUserName = strUserName EWorkRecord.EOnworkTime = EOnwork.EOnworkTime EWorkRecord.EOffworkTime = Now BOffwork.Offwork(strUserName,EWorkRecord) Me.Close() Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub Frmmain_FormClosing(ByVal sender As Object,"提示") = vbCancel Then e.Cancel = True End If End Sub
结果:点击确定退出时,还是会发生死循环,当然还是me.close()惹的祸,调试一遍恍然大悟,这两个方法有什么区别呢?formclosing() 是窗口的正在关闭事件,而formclosed() 却是窗口已经关闭的事件,窗口都已经关闭了还要me.close()做甚呢? 所以正确写法如下:
Private Sub Frmmain_FormClosed(ByVal sender As Object,EWorkRecord) Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub Frmmain_FormClosing(ByVal sender As Object,"提示") = vbCancel Then e.Cancel = True End If End Sub原文链接:https://www.f2er.com/vb/260822.html