Vig*_*r A 9 .net vb.net excel garbage-collection
我设计了一个.net应用程序,它将在登录时打开一个excel文件并用它来打印报告.注销用户时将关闭它.我为excel文件设置了可见的false,因此用户不知道后台进程.
但是如果有人在此期间打开任何其他excel文件,我的报告excel文件将变为可见,并且excel对象将折叠.我必须去任务管理器并杀死所有打开的excel实例来解决这个问题.
码:
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Try
Dim dt As New DataTable()
Dim Adapter As New SqlDataAdapter()
ConnectMe()
Dim SQLCmd As New SqlCommand("uspLogin", Con)
SQLCmd.CommandType = CommandType.StoredProcedure
SQLCmd.Parameters.AddWithValue("@pLoginName", UsernameTextBox.Text.Trim())
SQLCmd.Parameters.AddWithValue("@pPassword", PasswordTextBox.Text.Trim())
Adapter.SelectCommand = SQLCmd
Adapter.Fill(dt)
SQLCmd.Dispose()
If dt.Rows.Count > 0 Then
Me.Cursor = Cursors.WaitCursor
Loading.Show()
OpenAllTempaltes()
Me.Hide()
Con.Close()
Me.Cursor = Cursors.Arrow
Else
MsgBox("Your Credential is Wrong !!!", MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "Login")
UsernameTextBox.Text = ""
PasswordTextBox.Text = ""
UsernameTextBox.Focus()
End If
Catch ex As Exception
Application.Exit()
End Try
End Sub
Public Sub OpenAllTempaltes()
Try
xlWorkBook = xlApp.Workbooks.Open(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Templates", "Excel_Templates_GST.xlsm"), Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, True)
Catch ex As Exception
Throw
End Try
End Sub
Public Sub CloseAllTempaltes()
Try
CleanUp(xlApp, xlWorkBook, xlWorkSheet)
Catch ex As Exception
ExceptionLog("PrintPage", "CloseAllTempaltes", ex.ToString(), DateTime.Now.ToString("dd-MMM-yyyy"))
Finally
GC.Collect()
End Try
End Sub
Run Code Online (Sandbox Code Playgroud)
请帮我解决如何防止这种情况.
Aji*_*thy 10
使用IgnoreRemoteRequests
Excel应用程序对象的属性:
xlApp.IgnoreRemoteRequests = True
这相当于在
File | 中检查Excel UI选项 选项| 高级| 一般| 忽略使用动态数据交换(DDE)的其他应用程序.
(请参阅SuperUser上的相关答案.)
我无法使用.NET应用程序方便地重现您的场景,但是通过延迟绑定Word VBA中的Excel.Application对象来运行一些测试并且它按预期工作.我创建了一个隐藏的Excel应用程序,并且能够通过双击文件资源管理器在打开文件之前和之后对其执行操作.
在我的测试中,下次正常打开Excel时,设置仍未切换,但您可能希望在退出应用程序对象之前捕获其值并恢复它,以防该行为不是通用的.
编辑:此行为至少从Excel 2003开始,我使用Excel 2016(32位)验证.
在Excel 2013或更高版本中,Excel切换到单个文档界面:每个工作簿在其自己的窗口中打开.
至少到2016年,Visual Basic编辑器仍然是一个多文档界面,您可以通过查看VBE中的Project Explorer窗格轻松查看应用程序会话中打开的文件.