当我点击红色X按钮关闭表单时,我有以下代码应该在后台工作程序中运行:
Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
picLoading.Visible = True
tblMain.Visible = False
bwQuitNoSave.RunWorkerAsync()
End Sub
Private Sub bwQuitNoSave_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwQuitNoSave.DoWork
'If at least one sheet has been opened, close the workbook
If FirstLoad = 2 Then
worksheet.Cells(1, 31).Value = ""
workbook.Save()
workbook.Close(False)
End If
End Sub
Private Sub bwQuitNoSave_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bwQuitNoSave.RunWorkerCompleted
'Exit the application
APP.Quit()
End Sub
所以应该发生的是应用程序检查是否为整数= 2,如果是,则保存工作簿,关闭它,然后退出应用程序。但是,当我运行此代码时,即使应用程序关闭,excel进程也会保持打开状态。
在我的应用程序的上一次迭代中,我正在使用正常运行的代码(例如,关闭了excel进程):
Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
picLoading.Visible = True
tblMain.Visible = False
'If at least one sheet has been opened, close the workbook
If FirstLoad = 2 Then
worksheet.Cells(1, 31).Value = ""
workbook.Save()
workbook.Close(False)
End If
'Exit the application
APP.Quit()
End Sub
有人看到我遗失的东西吗?
我也试过了,这个过程仍然是开放的:
Private Sub bwQuitNoSave_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwQuitNoSave.DoWork
'If at least one sheet has been opened, close the workbook
If FirstLoad = 2 Then
worksheet.Cells(1, 31).Value = ""
workbook.Save()
workbook.Close(False)
End If
Try
workbook.Close(False)
APP.Quit()
Catch
APP.Quit()
End Try
End Sub
Private Sub bwQuitNoSave_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bwQuitNoSave.RunWorkerCompleted
'Exit the application
releaseMemory(APP)
releaseMemory(worksheet)
releaseMemory(workbook)
End Sub
Private Sub releaseMemory(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
经过多次尝试后解决了这个问题:
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If e.CloseReason = CloseReason.UserClosing Then
e.Cancel = True
picLoading.Visible = True
tblMain.Visible = False
If FirstLoad = 2 Then
worksheet.Cells(1, 31).Value = ""
bwQuitNoSave.RunWorkerAsync()
Else
Quit()
End If
End If
End Sub
Public Sub Quit()
APP.Quit()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
Application.Exit()
End Sub
Private Sub bwQuitNoSave_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwQuitNoSave.DoWork
'If at least one sheet has been opened, close the workbook
workbook.Save()
End Sub
Private Sub bwQuitNoSave_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles bwQuitNoSave.RunWorkerCompleted
Quit()
End Sub
事实证明关键是通过红色X取消退出并手动关闭应用程序。