You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中关闭主窗体Form1返回登录页时Application.Run报错如何解决

报错原因

Application.Run(New Form1)会将传入的Form1绑定为应用程序的主窗体,主窗体关闭时默认会终止应用程序的消息循环,你当前的写法在Form1的销毁流程中直接弹出FormLogin、同时入口Sub Main的逻辑只会执行一次,没有循环承接下一次主窗体启动,就会触发上下文已释放、进程即将退出类的报错。

修复方案

第一步:修改入口Sub Main逻辑,增加循环承接登录-启动主窗体的流程

' 入口Sub Main代码
While True
    If FormLogin.ShowDialog() = DialogResult.Yes Then
        Try
            Application.Run(New Form1)
        Catch ex As Exception
            MsgBox("程序运行异常:" & ex.Message)
        End Try
    Else
        ' 用户在登录页选择退出,才真正终止程序
        Application.Exit()
        Exit While
    End If
End While

第二步:简化Form1的关闭/退出登录逻辑

删掉你之前写的Dispose()、FormLogin.ShowDialog()相关代码,退出登录时只需要正常关闭Form1即可,控制权会自动交回Sub Main的循环,触发下一轮登录流程:

' Form1内退出登录按钮的逻辑
Me.Close()
可选扩展:区分「退出登录」和「直接关闭应用」

如果需要实现用户点主窗体右上角关闭按钮时直接退出整个程序,只有点「退出登录」按钮才回到登录页,可以按以下方式修改:

  1. 在Form1的代码中新增公共标记属性
' Form1类内顶部添加
Public IsLogout As Boolean = False
  1. 修改Form1的退出登录按钮逻辑
' 退出登录按钮点击事件
IsLogout = True
Me.Close()
  1. 调整Sub Main的逻辑,增加标记判断
While True
    If FormLogin.ShowDialog() = DialogResult.Yes Then
        Try
            Dim mainForm As New Form1
            Application.Run(mainForm)
            ' 判断用户是不是主动点了退出登录
            If Not mainForm.IsLogout Then
                ' 不是退出登录,直接结束整个程序
                Application.Exit()
                Exit While
            End If
        Catch ex As Exception
            MsgBox("程序运行异常:" & ex.Message)
        End Try
    Else
        Application.Exit()
        Exit While
    End If
End While

内容的提问来源于stack exchange,提问作者Caleb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:45:04