Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  HOME    TRACKER    Visual Basic

Process Termination Notification


I'm trying to notify a program (progA), from which I launched another application (progB) using the shell(progB) function, of the scond program's (progB's) termination.

Does ANYONE have any idea (specifics please) on how to accomplish this?


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Process Termination
What is the best way to add code to ensure the process terminates and doesn't stay in memory?

Detecting Process Termination
Hello Forum!
I want to know how can I detect when a program that I have launched from my project is unloaded, but no checking all the time the processes runing, I think this would involve some subclassing or pipes...
anyone can help me on this?

Thanks in advance.

Avoiding Process Termination
How can I avoid users to stop my application, it is very simple to do it using two programs that check for each other, but i dont want that!
I want something that cannot be closed in the Windows TaskManager, not even by killing the application process (this is the main issue here)!!
I need to make this work under Windows XP & Windows 2000

Shell Command - Process Termination
I need to use the shell command to execute a .bat file. I also need to know when the process finishes, but the following portion of VB's help for the shell command illustrates my troubles trying to do so:

Note By default, the Shell function runs other programs asynchronously. This means that a program started with Shell might not finish executing before the statements following the Shell function are executed.

So, if I write a test.bat file for testing purposes, which contains the single line:

Pause "Press any key to continue..."

And I try to include a call to this file in a test function, coded as follows:

If Shell("c: est.bat") Then
MsgBox "Test was successful!"
MsgBox "Test was unsuccessful!"
End If

I find that, true to the words from VB's help (see above), I get the message box saying, "Test was successful", displayed while the DOS window is still open, displaying the "Press any key to continue..." message. I then click "OK" on the message box, then click on the dos window to set focus there, press any key, and the window disappears.

Is there any way I can test for when a shell session has ended? I really need to be able to do this to know when it is time to check for the results of having run the .bat file I will actually be using.

Thanks ahead for help.

Notification From A VB DLL To The Parent Process
How can a VB DLL provide event notification to its parent
process. I have a DDL that contains a winsock control and
I want to notify the main program that data has arrived.
Any Ideas out there?


Adding Email Notification To My Process
Hello All,
I have a process that updates a access database.
I want to add a simple email notification piece to it in order to inform the users when the process is done.
Attached is my current code. Any ideas please...!!!

CODE' Loads the process_db form to start the process.
Private Sub Form_Load()
Me.Visible = False
Call process_db
Unload Me
End Sub
Private Sub process_db()
' Process begins here

'Create Preload Log File
Dim txtStream As TextStream
Set fso = New FileSystemObject
Set txtStream = fso.CreateTextFile("c:ThorVivekThor.htm")

'Rename the M:FTPFILESThorPRAQ136D-THOR-EXTRACT.D0 file to M:FTPFILESThorPRAQ136D-THOR-EXTRACT.txt for importing to access - Start

Dim FileName1 As String
Dim NewFileName1 As String
On Error Resume Next

Name FileName1 As NewFileName1
'Rename the file to .txt for importing to access - Complete

'Macro start to do the import to the Raw table - Start
    txtStream.WriteLine "Thor Macro Start" & CStr(Now)
    Dim accobj As Access.Application
    Set accobj = CreateObject("Access.Application")
    ' Set database path to web folder on IOSC Web
    accobj.OpenCurrentDatabase ("C:ThorVivekBackend.mdb")
    accobj.DoCmd.RunMacro ("Process")
    Set accobj = Nothing
    txtStream.WriteLine "Thor Macro End" & CStr(Now)
'Macro start to do the import to the Raw table - End
'Rename the PLTDLODD.txt fileto PLDTDLODD.d0 for importing to access - Start
'Rename Apps Table
Dim FileName5 As String
Dim NewFileName5 As String
On Error Resume Next

Name FileName5 As NewFileName5

'Rename the .txt file to .d0 for importing to access - Complete
    'File path as per Deepak's machine
    txtStream.WriteLine "Compaction Start" & CStr(Now)
   ' DBEngine.CompactDatabase "C:TestThorBackend.mdb", "C:TestThorCompactBackend.mdb"
    DBEngine.CompactDatabase "C:ThorVivekBackend.mdb", "C:ThorVivekCompactBackEnd" & Month(Date - 1) & "-" & Day(Date - 1) & Year(Date - 1) & ".mdb"
    txtStream.WriteLine "Compaction End" & CStr(Now)
    txtStream.WriteLine "File Copy Start" & CStr(Now)
    fso.CopyFile "C:ThorVivekCompactBackEnd" & Month(Date - 1) & "-" & Day(Date - 1) & Year(Date - 1) & ".mdb", "T:ThorBackendBackend.mdb"
    txtStream.WriteLine "File Copy End" & CStr(Now)
    txtStream.WriteLine "File Copy Start Back to Local Drive for Fresh Compacted Version" & CStr(Now)
    fso.CopyFile "C:ThorVivekCompactBackEnd" & Month(Date - 1) & "-" & Day(Date - 1) & Year(Date - 1) & ".mdb", "C:ThorVivekBackend.mdb"
    txtStream.WriteLine "File Copy End" & CStr(Now)
    txtStream.WriteLine "File Copy Start to Cedar Rapids" & CStr(Now)
    fso.CopyFile "C:ThorVivekBackend.mdb", "N:IFSBackend.mdb"
    txtStream.WriteLine "File Copy End" & CStr(Now)
End Sub

Notification For Process Complete Using Windows Schedular
Hello All,
I am couple of process that run daily on my computer using WIndows Scheduler.
Is there any feature within Windows Scheduler to notify if a process is complete. May be email.
If there are any other suggestions please let me know..
Are there any freeware tools which can do this...

Thanks in advance..

A good programmer is someone who looks both ways before crossing a one-way street. - Doug Linder

The Termination Box.
I'm having this rather small problem, or thats what I think it is.

Basically when someone attempts to click the "CLOSE" box on the top right of the program, a message box will appear saying "Do you wish to save any changes?" If the user clicks Yes, It'll make the necessary changes to the program (updates). If the user clicks No, It'll make no changes and will terminate the program immediately.

Isn't Form_Terminate() Responsible for this? I tried coding and testing it. It made no acknowledgement and just closes.

What am I doing wrong? The coding is below

Private Sub Form_Terminate()
Dim intResponse As Integer
intResponse = MsgBox("Do you wish to Save any Changes?", _
vbYesNo + vbQuestion, _
"Exit Database System")

If intResponse = vbNo Then
End If
End Sub

Or does Form_Terminate() do something I didn't know about? I'm a little confused.


When a vb exe is terminated from the task manager or process list, is the Form_Terminate() event executed?

I don't think the End Statement is living up to its name. For some reason after my executable version of my projects have been exited (code used was "End") it is still running in the background (Ctrl+Alt+Del is only way to close it). Something I'm missing?

Hello all.

I want to unload another application from my current application.
For example, if i want to make it so that when someone loads my application two times, the second time he loads it, it unloads the first instance and the second instance of application.
Its easy to unload current instance but what about the earlier one?
Heres what i mean:

private sub Form_Load()
    if app.previnstance=true then
    'part of code that should unload earlier and current instances of application
    end if

end sub

Also, what do i do when i want to unload ANY process? I know API for process termination:
Declare Function TerminateProcess Lib "kernel32" Alias "TerminateProcess" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long,

 but how do i get process indetifier? Is it exe name or what?
Thanx for you help

Windows has detected mouse movement!

Please restart your system so that changes can take effect !!!

Excel Termination
I have sent similar post some time back... but same porblem still exisitng

I cannot relerase / Quit from Excel application, it is still in the task managerthough I am releasing all variables. Pls help me

Private Sub cmdProcess_Click()

Dim lstrFrom As String
Dim lstrTo As String
Dim lintDivision As Integer
Dim i As Integer
Dim lintCountryRow As Integer
Dim lintTitleRow As Integer
Dim lintReturnValue As Integer

If txtFromYear.Text = "" Or txtToYear.Text = "" Then
MsgBox "Please enter the Start and End Financial Years", vbCritical, Me.Caption
Exit Sub
End If

If Not gblObjExcel Is Nothing Then
Set gblObjExcel = Nothing '<....................To release from the Memory
End If

Set gblObjExcel = New Excel.Application
Set gblObjWorkBook = gblObjExcel.Workbooks.Open(App.Path & "New_ReportsTOP_PAX.XLS")
Set gblObjWorkSheet = gblObjWorkBook.Worksheets(1)

'gblObjExcel.Visible = True

lintDivision = Val(txtToYear.Text) - Val(txtFromYear.Text)
i = 0
lintTitleRow = 3
Do While i <= lintDivision
lintReturnValue = ProcessMe(txtToYear.Text - i, 1, lintTitleRow, lintTitleRow + 1)
lintTitleRow = lintReturnValue + 2
If i < lintDivision Then: Write_Months lintTitleRow + 1
i = i + 1

On Error Resume Next
Kill gblStrExcelFilePath & "TOP.XLS"
On Error GoTo 0

gblObjWorkBook.SaveAs gblStrExcelFilePath & "TOP.XLS"

MsgBox "Report Saved in " & gblStrExcelFilePath

Set gblObjWorkSheet = Nothing
Set gblObjWorkBook = Nothing
Set gblObjExcel = Nothing

End Sub

Public Function ProcessMe(lstrfromDate As String, lintCtryTileRow As Integer, lintyearTitlerow As Integer, lintExcelRow As Integer) As Integer

Dim lobjConn As clsConnection
Dim lrstGlobalStat As ADODB.Recordset
Dim lrstOtherCountrieStat As ADODB.Recordset
Dim lrstCYUD As ADODB.Recordset

Dim lstrSql As String
Dim lstrToDate As String
Dim i As Integer
Dim j As Integer
Dim lstrConCatenatedAgents As String

Dim lstrStartDate As String
Dim lstrEndDate As String
Dim lintMonthNumber As Integer
Dim lstrActualMonth As String
Dim lstrCurrentMonth As String
Dim lstrCurrentYear As String
Dim lintDataMonth As Integer

Dim ldblMainCountry_CYUD As Double
Dim ldblOtherCountry_CYUD As Double

Dim lstrCYUD_StartDate As String
Dim lstrCYUD_ENDDATE As String
Dim lCol As Integer
Dim lRow As Integer
Dim lRowindex As Integer

Set lobjConn = New clsConnection

'Format and the values of the Financial dates
lstrStartDate = lstrfromDate & "04"
lstrEndDate = (Val(lstrfromDate) + 1) & "03"

'For CyUD Query
lstrCurrentMonth = Mid(Format(Date, "YYYYMM"), 5, 2)
lstrCYUD_StartDate = lstrfromDate & "04"

If Val(lstrCurrentMonth) < 4 Then
lstrCYUD_ENDDATE = (lstrfromDate + 1) & lstrCurrentMonth
lstrCYUD_ENDDATE = lstrfromDate & lstrCurrentMonth
End If

'Keeping checked items in the list and concatenating the Agents codes( Grid should show only Cecked items unltimately )
i = 1
j = 1
Do While i <= listvAgency.ListItems.Count
If listvAgency.ListItems(i).Checked <> True Then
listvAgency.ListItems.Remove i
i = i - 1
If j = 1 Then
lstrConCatenatedAgents = "'" & listvAgency.ListItems(i).SubItems(3) & "'"
ElseIf j > 1 And j < listvAgency.ListItems.Count Then
lstrConCatenatedAgents = lstrConCatenatedAgents & "," & "'" & listvAgency.ListItems(i).SubItems(3) & "'"
End If
j = j + 1
End If
i = i + 1

If Not j > 1 Then
MsgBox "Please Select At least One country to display"
ProcessMe = 10000
Exit Function
ElseIf j > 100 Then
MsgBox "Pls"
End If
'Main Country Query
lstrSql = "Select V.Tour_Operator TOP,V.Tour_Operator_Name TOP_NAME, to_char(V.YEAR_MONTH,'YYYYMM') MONTH_YEAR, " _
& "Sum(nvl(V.EK_PAX,0) + NVL(V.Non_Ek_Pax,0)) PAX " _
& "Where V.Product_Code='" & cboProduct.Text & "' AND " _
& "V.TOUR_OPERATOR in (" & lstrConCatenatedAgents & ")" & "And " _
& "V.Country_Name='" & cboCountry.Text & "' AND " _
& "To_Char(V.YEAR_MONTH ,'YYYYMM') between " & lstrStartDate & " AND " & lstrEndDate & "" _
& " Group by V.Tour_Operator,V.Tour_Operator_Name, to_char(V.YEAR_MONTH,'YYYYMM')"

Set lrstGlobalStat = lobjConn.MyGetResults(lstrSql)
'Other Country Query
lstrSql = "Select to_char(V.YEAR_MONTH,'YYYYMM') MONTH_YEAR, " _
& "Sum(nvl(V.EK_PAX,0) + NVL(V.Non_Ek_Pax,0)) PAX " _
& "Where V.Product_Code='" & cboProduct.Text & "' AND " _
& "V.TOUR_OPERATOR NOT in (" & lstrConCatenatedAgents & ")" & "And " _
& "V.Country_Name='" & cboCountry.Text & "' AND " _
& "To_Char(V.YEAR_MONTH ,'YYYYMM') between " & lstrStartDate & " AND " & lstrEndDate & "" _
& "Group by to_char(V.YEAR_MONTH,'YYYYMM')"
Set lrstOtherCountrieStat = lobjConn.MyGetResults(lstrSql)

'----------MAIN COUNTRIES Report Writing-------------------------------------------------------------------------------------------
If lrstGlobalStat.EOF = False And lrstGlobalStat.BOF = False Then
'Country name
gblObjWorkSheet.Cells(2, 1) = "COUNTRY: "
gblObjWorkSheet.Cells(2, 2) = cboCountry.Text
gblObjWorkSheet.Cells(lintyearTitlerow, 1) = "FY Period: "
gblObjWorkSheet.Cells(lintyearTitlerow, 1).Font.Color = vbRed
gblObjWorkSheet.Cells(lintyearTitlerow, 2) = lstrfromDate

lRowindex = lintExcelRow
Do While lrstGlobalStat.EOF = False
lintMonthNumber = Mid(lrstGlobalStat.Fields("MONTH_YEAR"), 5, 2)
If lintMonthNumber > 3 Then
lCol = lintMonthNumber - 2
lCol = lintMonthNumber + 10
End If
'If previous TOP name is same as the current TOP name then row number is same, or else row number should change to next row
If gblObjWorkSheet.Cells(lRowindex, 1) <> lrstGlobalStat.Fields("Top_Name").Value Then
lRowindex = lRowindex + 1
gblObjWorkSheet.Cells(lRowindex, 1) = lrstGlobalStat.Fields("TOP_NAME").Value

lstrSql = "Select sum(nvl(P.Ek_Pax,0) + Nvl(P.Non_Ek_Pax,0)) PAX " _
& "From aa_v_agent_product_actuals P " _
& "Where to_char(p.year_month,'YYYYMM') between '" & lstrCYUD_StartDate & "' AND '" & lstrCYUD_ENDDATE & "' " _
& "AND P.COUNTRY_NAME='" & cboCountry.Text & "' " _
& "AND P.PRODUCT_CODE='" & cboProduct.Text & "' " _
& "AND P.TOUR_OPERATOR_NAME='" & lrstGlobalStat.Fields("TOP_NAME").Value & "'"

Set lrstCYUD = lobjConn.MyGetResults(lstrSql)
If lrstCYUD.EOF = False And lrstCYUD.BOF = False Then
gblObjWorkSheet.Cells(lRowindex, 15) = lrstCYUD.Fields("PAX").Value
End If
End If
gblObjWorkSheet.Cells(lRowindex, lCol) = Val(lrstGlobalStat.Fields("Pax").Value & "")
ldblMainCountry_CYUD = ldblMainCountry_CYUD + Val(lrstGlobalStat.Fields("Pax").Value)

End If
'----------------------------------OTHER COUNTRIES Report Writing-----------------------------
If lrstOtherCountrieStat.EOF = False And lrstOtherCountrieStat.BOF = False Then
lRowindex = lRowindex + 1
gblObjWorkSheet.Cells(lRowindex, 1) = "Others"
Do While lrstOtherCountrieStat.EOF = False
lintMonthNumber = Mid(lrstOtherCountrieStat.Fields("MONTH_YEAR"), 5, 2)
If lintMonthNumber > 3 Then
lCol = lintMonthNumber - 2
lCol = lintMonthNumber + 10
End If
gblObjWorkSheet.Cells(lRowindex, lCol) = lrstOtherCountrieStat.Fields("Pax").Value
End If

ProcessMe = lRowindex + 1

Set lobjConn = Nothing
Set lrstGlobalStat = Nothing
Exit Function

End Function

Public Sub Write_Months(lRow)

Dim n As Integer
Dim r As Range

gblObjWorkSheet.Cells(lRow, 1) = "Agent"
gblObjWorkSheet.Cells(lRow, 2) = "April"
gblObjWorkSheet.Cells(lRow, 3) = "May"
gblObjWorkSheet.Cells(lRow, 4) = "June"
gblObjWorkSheet.Cells(lRow, 5) = "July"
gblObjWorkSheet.Cells(lRow, 6) = "Ausgust"
gblObjWorkSheet.Cells(lRow, 7) = "September"
gblObjWorkSheet.Cells(lRow, 8) = "October"
gblObjWorkSheet.Cells(lRow, 9) = "November"
gblObjWorkSheet.Cells(lRow, 10) = "December"
gblObjWorkSheet.Cells(lRow, 11) = "January"
gblObjWorkSheet.Cells(lRow, 12) = "February"
gblObjWorkSheet.Cells(lRow, 13) = "March"
gblObjWorkSheet.Cells(lRow, 14) = "Total"
gblObjWorkSheet.Cells(lRow, 15) = "CYUD"

Set r = Range("A1:K1")
For n = 1 To 15
r.Cells(lRow, n).Cells.Interior.Color = &HC0C0C0
r.Cells(lRow, n).Font.Size = 8
r.Cells(lRow - 1, n).Font.Size = 8
r.Cells(lRow, n).Font.Bold = True

End Sub

Excel Termination
This been questioned & answered several times, But I have worked out as mentioned in the posts, but no luck yet

How to release the memory of the Excel application through VB??? I am closing the application through code, setting the objects to nothing but still the problem is exsiting

Finally I am trying to catch the Excel application id and would like to terminate the process by saying 'end task', but I am not able to catch the process Id of the excel (I hv opened through early binding methods)

Please put some light on this.

Here is my code:

'Creating instaces
Dim lobjExcel As Excel.Application
Dim lobjWorkBook As Excel.Workbook
Dim lobjWorkSheet As Excel.Worksheet

Set lobjExcel = New Excel.Application
Set lobjWorkBook = lobjExcel.Workbooks.Open(App.Path & "ReportsRep_Other_Market_Analisys.xls")
Set lobjWorkSheet = lobjWorkBook.Worksheets(1)

'Some code related to Database'
'Saving the excel file
lobjWorkBook.SaveAs pstrExcelFilePath & "Rep_Other_Market_Analisys.xls"

Set lobjWorkSheet = Nothing
Set lobjWorkBook = Nothing

Set lobjExcel = Nothing

Program Termination...

i have a program which is not suppose to close even if you try to kill it using the windows task manager in windows xp or 2000.

Now what technique i used to protect it from closing

Whenever user tried to kill it using windows task manager it would get killed but before getting killed it started a new instance of the program. This technique worked until i had no code in Form_Unload() but as soon as i had inserted some code in Form_Unload() it gets killed and does not starts a new instance.

Why the Form_Unload() is loaded when the program is being terminated ?

Is there any better technique to do that ?


Program Termination
I think I must be forgetting something for my program the end of my one (and only) module, I set all objects = to nothing and include an exit sub before the error handling, but my program tends to keep running anyway in debug mode (every now and then, when there are no breakpoints set, it ends normally.) I compiled into an exe and the program definitely doesn't terminate - it does everything that it's supposed to but if I run a few times then hi ctrl+alt+delete, I saw multiple instances of the program still code is below....can anyone help?


Option Explicit
Dim TempConnection As New ADODB.Connection
Private Sub Main()

Dim i As Long

Dim database_name As String
Dim table_name As String
Dim temp_recordset As ADODB.Recordset
Dim LastName As String
Dim FirstName As String
Dim tmp_sql As String
Dim NameID As String
Dim lngNameID As Long
Dim NewEvent As String
Dim NewDate As String
Dim dtmNewDate As Date
Dim ContactName As String
Dim lngContactID As Long

Dim check_recordset As ADODB.Recordset
Dim record_exists As Boolean

Dim fullstring As String
Dim NewArray() As String
Dim SizeArray As Long

Dim ChangeString As String
Dim delimiter1 As String
Dim delimiter2 As String

Dim email_array() As String
Dim default_email As String

On Error GoTo main_error:

database_name = "\PikachuwwwrootServicesEduMeg.SandboxdbEvents2TestContactJun7.mdb"
table_name = "tblDirContacts"
default_email = ""

connect_to_database (database_name)

Dim FSO As New FileSystemObject, InFile As File, ts As TextStream
Set InFile = FSO.GetFile("\PikachuwwwrootServicesEduMeg.SandboxdbEvents2agendacomma.txt")

'if agenda file exists
If FSO.FileExists(InFile) Then
Set ts = InFile.OpenAsTextStream(ForReading)
'retrieve all data and close file
fullstring = ts.ReadAll

'Change any apostrophe marks into code
fullstring = Replace(fullstring, "'", "'")
'uses vb code for carriage return
delimiter1 = Chr(34) & vbCrLf & Chr(34)
'uses decimal ascii code for double quote
delimiter2 = Chr(34) & "," & Chr(34)

ChangeString = Replace(fullstring, delimiter1, delimiter2)

'split file entries into an arrary
NewArray = Split(ChangeString, delimiter2, , vbBinaryCompare)
SizeArray = UBound(NewArray)
ReDim email_array(0)

'for each entry in the file
For i = 12 To SizeArray Step 12
'retrieve date,event, and name
NewDate = Trim(NewArray(i + 1))
NewEvent = Trim(NewArray(i + 5))
ContactName = Trim(NewArray(i + 11))
If InStr(1, ContactName, vbCrLf, vbBinaryCompare) Then
ContactName = Replace(ContactName, vbCrLf, " ", , , vbBinaryCompare)
End If
'trim contact name into last name only
If InStr(1, ContactName, ",") > 0 Then
LastName = Trim(Left(ContactName, InStr(1, ContactName, ",") - 1))
FirstName = Trim(Right(ContactName, Len(ContactName) - InStr(1, ContactName, ",") - 1))
End If
tmp_sql = "SELECT lngContactID from " & table_name & " WHERE (strLastName = '" & LastName & "');"
'get all entries from table that include lastName
Set temp_recordset = TempConnection.Execute(tmp_sql)
'reset nameID
NameID = ""
'if no records were returned
If (temp_recordset.BOF And temp_recordset.EOF) Then
NameID = " "
lngNameID = 0
Else ' records were returned
NameID = Trim(temp_recordset(lngContactID))
lngNameID = CLng(NameID)
End If
dtmNewDate = CDate(NewDate)

'see if entry already exists in table
'grab all records from event table
Set check_recordset = TempConnection.Execute("SELECT * from tblEvent;")

record_exists = False

'if any records were returned
If Not (check_recordset.BOF And check_recordset.EOF) Then
'for each returned record
Do While Not check_recordset.EOF
'if fields match
If Trim(check_recordset.Fields(4).Value) = NewEvent Then
If Trim(check_recordset.Fields(2).Value) = dtmNewDate Then
'already in table
record_exists = True
Exit Do
End If
End If
End If

'if the event is already in the table
If record_exists Then
'do not add
Else 'add
'insert entries into table
tmp_sql = "INSERT INTO tblEvent (strEventName, dtmEventBegin, lngHostContact, lngEventTypeID, lngLocOrg) VALUES ('" & NewEvent & "', '" & dtmNewDate & "','" & lngNameID & "', '8', '453055410');"
TempConnection.Execute (tmp_sql)
'add name and email address to list of people to email

'if a name was found
If lngNameID <> 0 Then
ReDim Preserve email_array(UBound(email_array) + 3)
email_array(UBound(email_array) - 2) = Trim(ContactName)
email_array(UBound(email_array) - 1) = ""
email_array(UBound(email_array)) = "Dear " & Trim(FirstName) & " " & Trim(LastName) & ", " & vbCrLf & "An automatic update to the calendar has occured and changes have affected one the following entries:" & vbCrLf & NewEvent & ", " & NewDate & vbCrLf & "Please view these changes and verify that they are correct. <Link to file here>" & vbCrLf & "Reply to:"
Else 'if no name was found
ReDim Preserve email_array(UBound(email_array) + 3)
email_array(UBound(email_array) - 2) = "Event Owner"
email_array(UBound(email_array) - 1) = Trim(default_email)
email_array(UBound(email_array)) = "Dear Event Owner, " & vbCrLf & "An automatic update to the calendar has occured and changes have affected one the following entries:" & vbCrLf & NewEvent & ", " & NewDate & vbCrLf & "Please view these changes and verify that they are correct. <Link to file here>" & vbCrLf & "Reply to:"
End If
End If
Next i
Else 'no file was found
GoTo corporate_time_file_error
End If

'for each person in email list
For i = 1 To UBound(email_array) Step 3
If email_array(i) <> "" Then
'call email generating routine
frmInvis.send_email "", "Update Alert", email_array(i), "", email_array(i + 1), "Calendar update", email_array(i + 2)
End If
Next i

Set TempConnection = Nothing
Set temp_recordset = Nothing
Set check_recordset = Nothing

Exit Sub

On Error Resume Next

'try and generate an email to the owner and let them know app had trouble
frmInvis.send_email "", "Error Alert", "", "", "", "Error in Main", "Dear User," & vbCrLf & "The database application failed in the Main subroutine. Please troubleshoot the application and check the appropriate tables so see that data was entered correctly and emails were generated for updates."

'close database connection

Exit Sub


On Error Resume Next

'try and generate an email to the owner and let them know app had trouble
frmInvis.send_email "", "Error Alert", "", "", "", "Error in Main", "Dear User," & vbCrLf & "The database application failed in the Main subroutine. The corporate time file did not exist or could not be found. Please troubleshoot the application and check the appropriate tables so see that data was entered correctly and emails were generated for updates."

'close database connection

Exit Sub

End Sub
Sub connect_to_database(database_name As String)

On Error GoTo connect_to_database_Error:
With TempConnection

.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source = " & database_name & ";"
.CursorLocation = adUseClient

End With

Exit Sub

On Error Resume Next 'in case connection can't close

'try and generate an email to the owner and let them know app had trouble
frmInvis.send_email "", "Error Alert", "", "", "", "Error in Main", "Dear User," & vbCrLf & "The database application failed in the database connection subroutine. A connection to the database could not be established."

Exit Sub

End Sub

PDFCreator Termination - Need Help
I am using PDFCreator to print multiple Excel sheets within a single workbook. Now the code below works wonderfully with one exception my app gets locked up at the following point:

VB Code:
Do Until Dir(sPDFPath & sPDFName) <> ""        DoEvents    Loop

The file is generated and is viewable in the appropriate folder however the loop statement doesn't relinquish control so I can terminate the function.

Here is my complete code:

VB Code:
Private Sub Command1_Click()Dim DefPrinter As String, sLen As Long, iPrn As Printer, hResult As Long, DefaultStorage As String        DefPrinter = Space$(255)    sLen = 255    hResult = GetDefaultPrinter(ByVal DefPrinter, sLen)    If hResult <> 0 Then DefPrinter = Left(DefPrinter, sLen - 1)    '********************************************************************************    SetDefaultPrinter "PDFCreator"    '********************************************************************************    Dim pdfjob As clsPDFCreator    Dim PDFName As String    Dim PDFPath As String     PDFName = "TRW_MultiPDF_TEST_" & Format$(Date, "dd-mm-yyyy") & ".pdf"    PDFPath = App.Path    Set pdfjob = New clsPDFCreator       'Make sure the PDF printer can start    If pdfjob.cStart("/NoProcessingAtStartup") = False Then        MsgBox "Can't initialize PDFCreator.", vbCritical + _                vbOKOnly, "Error!"        Exit Sub    End If     'Set all defaults    With pdfjob        .cOption("UseAutosave") = 1        .cOption("UseAutosaveDirectory") = 1        .cOption("AutosaveDirectory") = PDFPath        .cOption("AutosaveFilename") = PDFName        .cOption("AutosaveFormat") = 0    ' 0 = PDF        .cSaveOptions        .cClearCache    End With     Set oXLApp = New Excel.Application  'Create a new instance of Excel    Set oXLBook = oXLApp.Workbooks.Open(App.Path & "TRW_Template.xls") 'Open Daily Data Template        Dim TtlSheets As Long    Dim oXLSheets As Long        'Print the document to PDF    TtlSheets = oXLApp.Sheets.Count    For oXLSheets = 1 To Application.Sheets.Count        On Error Resume Next 'To deal with chart sheets        If Not IsEmpty(oXLApp.Sheets(oXLSheets).UsedRange) Then            oXLApp.Sheets(oXLSheets).PrintOut Copies:=1, ActivePrinter:="PDFCreator"        Else            TtlSheets = TtlSheets - 1        End If        On Error GoTo 0    Next oXLSheets     'Wait until all print jobs have entered the print queue    Do Until pdfjob.cCountOfPrintjobs = ActiveWorkbook.Sheets.Count        DoEvents    Loop     'Combine all PDFs into a single file and stop the printer    With pdfjob        .cCombineAll        .cPrinterStop = False    End With        Do Until Dir(sPDFPath & sPDFName) <> ""        DoEvents    Loop        oXLBook.Close SaveChanges:=False    Set oXLBook = Nothing    oXLApp.Quit                                   'Close/Disconnect from Excel    Set oXLApp = Nothing        pdfjob.cCloseRunningSession    Set pdfjob = Nothing    '********************************************************************************    SetDefaultPrinter DefPrinter    '********************************************************************************End Sub

Anyone have a better way to verify file creation and completion before termination that avoids this issue?

Termination Of Program

is there a final form/module through which the program exits upon the programs termination.

i wanted to use this form/module to do saving and housekeeping tasks.

e.g. saving all the excel files

Intances And Termination
Could any body tell me How to Unload an component from itself.
Eg: Active X exe
Class: Class1
On Command button click I need to terminate the whole component

Program Termination
Anyone who has used NT knows that if you want to kill one program or process, all you have to do is the ctrl-alt-del and then the program or process can be effectively killed... Is there an API call or some other way of incorperating this into a program?

Tasklist And Termination

How can i get a list of programs running (those listed on the taskbar) and then choose to terminate some of them? Is there any ways to verify or wait till these programs are successfully terminated before i carry on my execution?

I searched through the general vb questions threads but found myself more confused about processes and those on the taskbar.

I am using vb6 and intended to use the application on Win 9x and Win ME only.

Thanks for any advice.

Termination Fails
I call subroutine:

Private Sub progress()
Dim n As Integer
For n = 1 To 10000
If Forms.Count Then DoEvents
label1 = n
Next n
End Sub

and at the same moment I close the form. after Form_QueryUnload and Form_Unload events happen, the
program continues the loop and new Form instance loads
to the memory...
how to force app terminate?

Abnormal Termination
Hi, my application terminates abnormally after running a few hours, so far it has only terminated when application is unused for a few hours (minimized to tray). I will try leave it open for a few hours to see if the result is the same. (When minimized to tray I've made it so the application does not appear on task-menu, only on tray). When terminating, “Form Unload” and “Form Terminate” is not invoked, nor can I get an error message from the timer that runs every 1000 ms, and I get no error message what so ever. It just shuts down and disappears (both the tray-icon and it also disappears from processes in task-manager. I cant find anything in my code that should allow this to happen. And I have no idea on where to start searching for the error, nor how to find the error.

Anybody has a clue on what to search for, or how to figure out what happen. I have run Regmon when leaving application on tray (unused), and I enclose the log hoping that it may make a sense to someone. There's a lot going on there, a little to much when leaving the program without using it. My first thought was a declaration that overruns, but I'm not sure if this will crash without leaving a error message.

 Is there maybe an application that can scan my code for errors or an application that can monitor what goes wrong? Any ideas will be appreciated!

I tried to let the application be open (not minimized to tray) and it did not crash, so it seems that it only happens when minimized to tray.

Edited by - Savage on 5/29/2005 1:27:17 AM

Self Termination VB6 Application
Hi All,

I am trying to make an application that should terminate itself after 30-60 secs and then appear back again by clicking its icon.

I am using borderless form and need code for self termination of an application.

thank you in advance

Termination Of Running App.
Could anyone please tell me how can i terminate an application that is already running from a VB program? Please note that the application has started outside my program so i don't know its task ID. Also note that i wish to terminate it normally (i.e. request its termination, not force its termination).


[About Application Termination]

I wrote program that read the data from the input file and print to Excel97.
After loading the form, if I click my command button, it does work good first
time, but re-click my command button, it does not work.
I think my program doesn't have suitable termination process.

I wrote the following in my command button code


---- public xl as object
---- public wb as object
---- public ws as object

private sub my_command_click()
' Initialize the object
set xl = nothing
set wb = nothing
set ws = nothing

' Excel Object Creation
Set xl = CreateObject("excel.Application")
Set wb = xl.Workbooks.Add
set ws = wb.sheets(1)

$$ ---------- File reading and write to Excel Routine Here -----------

xl.visible = true

set xl = nothing
set wb = nothing
set ws = nothing

end sub

At second time, $$ mark line does not work.
How can I do ?

Have a nice day!

Unproper Termination Of MS Excel
Hi all,
I have a problem here....
I have this Visual Basic program where it will open a MS Excel spreadsheet storing of data.
then quit MS Excel visually, but in fact Ms Excel is still running in the background.

I did initlias the excel.application, excel.workbook, excel.worksheets(1) properly.

Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlsheet As Excel.Worksheet

Set xlApp = CreateObject("excel.application")
Set xlBook = xlApp.Workbooks.Open
Set xlsheet1 = xlBook.Worksheets(1)

When i am terminating it, i do stuff like


So why is there such problem?
Please advise...

How Can I Get Event Of Application Termination?
I want to do something such as, resource relase, Save settings, ..etc just before application is terminated.
How can I do this?
I can do that for each form using Form_Unload,
but, I need for an application.

thank you..

Check Abnormal Termination
How can i find out abnormal termination of my app by anyreason?.

i'm changing some system defaults when my app starts.. and i want to revese it when it close... but what if my app terminates abnormally??

is there any way to track it??

any help would be appriciated..

User Control Termination
I am having problems with user controls not terminating correctly. Their terminate event is not triggering when I close the form that contains them, only when the whole application is terminated. I know this because I have put a debug statement in their terminated event. The result of this is that the forms that contain them do not unload properly, so that their variables are not reinitialised on reloading, even though I have "Set frmOne =Nothing". What could be causing this?

Preventing The Program Termination
Hi to all,

How can I prevent the termination of the program when the user clicks on the close button (the cross at the most top and most right point of the form)? In fact, I donít want this event procedure leads to close the whole project. My project is a SDI and I want to load another form when the user clicked on the close button.

Application Termination Problem
I have a data acquisition program which is triggered by a start button using MScomm.

Private Sub cmd_start_Click()

dim statements.......

On Error GoTo errorhandler_1


'here the data acqusition takes place....

GoTo readdata
Exit Sub
MsgBox "error", vbOKOnly + vbExclamation, "Error"
End Sub

So once the start button is pressed the progarm enters an indefinite loop in the command button event procedure.
Now when the windows "X"button is being pressed the application is not terminating totally i.e windows task manager is still showing it as "running".

Only if I insert "End" command in the form unload procedure the application is terminating properly.

Please suggest whether this is reccomended.

Forcing Termination On A Program
How would i force a termination of a program by the name of that program?

Termination Of Program Using The End Keyword

In past post i had asked if the end button of the IDE is a good thing to use, and i was told thatit leaves behind quite a mess

I have this application which does a bit of excel automation.
and i now at some points need to terminate the program based on certain criteria, what i mean is this that the program will not run normally but terminate.

one way to do is just by using the end, but i think there will be lots of excel files left open, correct and perhaps the loaded forms will still be resident in the memory.

is there some sort of routine which will check for the excel objects and forms which are active or present in memory and kill them one of by one and then terminate the program? something which does a loop over say the collection of excel objects and something which does a loop over the collection of forms.

or do i need to do this manually?

Abnormal Program Termination

I' m working on a client-server application. When i'll try to delete a lot of records in adodb.recordset on client-side i'm getting an error "Visual C++ runtime error: Abnormal program termination". I'm getting this error on the 3th record. See Code Below.

5820 If Not vCodes Is Nothing Then
5830 For Each vKey In vCodes.Keys
5840 vRs.Filter = "Code = " & vCodes.Item(vKey)
5850 MsgBox 1
5860 If vRs.RecordCount > 0 Then vRs.Delete
5870 MsgBox 2
5880 vRs.Filter = adFilterNone
5890 DoEvents
5900 Next vKey
5910 Set vCodes = Nothing
5920 End If

Help please


Program Termination Error
I have a program which use tcpip communication, and terminate
if the line cannot be connected, before terminate, I use Socket.Close
to close all sockets already.

The socket close and End statement are in the Form_Unload event

For Win98SE, it works perfectly, but in Win2000 Professional, it keeps
giving me 'Program Abnormally terminate, Output to Error Log...' something like that
(since I am not using English window, so I cannot quote the message exactly)

I set breakpoint and find out that the whole program is working
as expected, only when the exit sub statement in the Form_Unload
will cause the problem. WHY?????

I am desparate and need to solve this before Monday, or DIE....

Help PLEASE !!!

Form Termination Trapping
I'd like to make my program run until the user exits with my exit command, and not the termination button. Is there anyway to trap that?

Preventing Application Termination
How would I prevent a user from exiting an application. I would like an application to "take over" the pocket pc. Removing the "X" at the top right of the screen would be nice. Any suggestions??? Thanks!

Question Regarding Unload And Termination Of VB Programs

Note When a form is unloaded, only the displayed component is unloaded. The code associated with the form module remains in memory.

This is a quote from MSDN in the VB6 Programmers Reference regarding the Unload statement - see the whole page here:

I was looking at this while thinking about another users problem ( ) and decided to look up the 'official' reference information.

It seems to me that the above qoute from MSDN is incorrect, or at least somewhat misleading - in the case of a simple one form program if you properly execute 'Unload Me' (with no further reference to any object on the form) does the process in fact terminate?

I'm thinking this concept could make for a good tutorial!

Opening A Form After Termination Of An EXE File
well the subject is self explanatory . basically I can open an exe file through a form by a comman button, but when I Exit from the exe application, I want my form to pop up, how can I do that? I used a shell command to open an exe file.
any suggestions?


Save Data Prior To Termination
hey guys, im having some trouble with a visual basic project im working on..
what i need to do is save some data to a text file when the program is terminated, and i cant really figure out how to do it. for example, if the program is running, and the user shuts down the computer or ends the process through the task manager, i need a certain sub to run before the program stops.

i tried searching but didnt come up with much...

ive tried putting the call for my sub in Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer) but it doesnt work, im not really sure what this actually does... maybe im using it incorrectly? also, it would seem like putting the call in the exit button would work, but that wouldnt really help here.

i read a post about running it program as a service, not sure if that would help here... i dunno

in the mean time, i have a timer set to it saves the data at certain time intervals, but hopefully there is a better way.

i hope i am explaining this good enough and sorry if its a stupid question.
thanks for the help.

Perserve Variable Value After Termination Of Application
I want to save dynamic value(string) after termination of application [in VB-6], so I can use that value after I restart the application.

I am trying by REGISTRY link, can you pls provide me code for that.

lets say:

VB Code:
dim x as stringx="heaven" [runtime/dynamic value]

I want value of x after I re-load the application.

can you ples resolve my problem, it seems simple.
Thank you very much.

Termination A Previous Instance Of My Application...
Anyone know a clean way of terminating a previous instance of my program?

I don't want to just detect the previous instance...(easy to do with app.previnstance). I want to kill it.

Serial String Termination && MSComm

I am trying to communicate to VB6 via a serial cable & the MSComm control uding a PIC microprocessor.

I can send the data from the PIC, which reaches the PC fine. I can view the data in hyperterminal, and i can see the data filling up the serial buffer from VB, I can also get the data using mscomm1.Input (once I know it is in the buffer). HOWEVER - the MSComm1_OnComm() event never seems to fire.

I know the data is there, but I cant work out why the event doest trigger. Does the sting need a termination code? I have tried CR, LF & 0xFF, but i cant seem to get it to work.

For anyone interested, the PIC Basic code used to send the data in the first place is; Code:SerOut PORTB.3, 16780, [DEC 3, 0xFF]
PORTB.3 is an output pin on the chip, 16780 means serial settings; '2400, N, 8, 1' the last bit is the data sent.

The reason I need the event to fire is that my code is a test for a piece of software that i cannot alter. It wasnt written in VB, but I assume it works along the same lines (as it doesnt work with the present set up).

Any ideas?

Error: Abnormal Program Termination (VB 6.)
I am executing a .cmd file in my VB 6.0 program. the .cmd file contains several steps including another .exe file. When I execute that .cmd file from command prompt it works fine but when I execute that .cmd file in my VB 6.0 program an error occurs for each .exe statement in .cmd file. The error is:
Runtime Error!

Program: [Exe file name]

abnormal program termination.

When I click OK button of that error message another message appear with title '[exe file name] Error'
and message: ... Mermory could not be read...

Please help me in this regard and suggest me the solution.


How To Call For A Premature Termination Of Code In A Timer?
Hello, everyone. Getting straight to business, the situation is as follows:

In my application, I have several forms, one of which is a loading form, which I use to load different forms. The form operates so that it first unloads the current active form, and then loads the requested form.
Sort of like this:

Sub cmdLoad_Click()
' Unloads current form, or form A
' Loads requested form, or form B
End Sub

The problem occurs when there is a timer still active in form A, that performs actions that require controls that are only available in form A.
Obviously, when the timer gets to a point where it tries to perform said actions, I'm getting an error because form A, and subsequently all controls belonging to it, are unloaded.

What I want to do is to terminate the execution of code in the timer. Is there any way to do this? I see no other solution to this problem.

Proper Modus Operandi For Termination Code
I have a menu bar and a close button. My program also contains numerous database connections that must be closed before exit. I'm just starting to add-in the menu functionality and I have come to an issue. Here is the code for my 'Close' button:

VB Code:
Private Sub cmdClose_Click()     DailyRS.Close                   SafetyDailyRS.Close             SafetyWeeklyRS.Close            SafetyFlashRS.Close             ScheduleRS.Close                Connection.Close                    Set DailyRS = Nothing               Set SafetyDailyRS = Nothing         Set SafetyWeeklyRS = Nothing        Set SafetyFlashRS = Nothing         Set ScheduleRS = Nothing            Set Connection = Nothing             UnloadAllEnd Sub

UnloadAll is in a module:

VB Code:
Option ExplicitPublic Sub UnloadAll(Optional Activefrm As Form)Dim Frm As FormDim Ctl As Control     On Error Resume Next        For Each Frm In Forms            If Frm.Name <> Activefrm.Name Then                For Each Ctl In Frm.Controls                    Set Ctl = Nothing                Next                Unload Frm                Set Frm = Nothing            End If        NextEnd Sub

This has worked well until I tried the menu 'Exit'. I need to close the db connections no matter how I close the program. However, if I try to place the connection.close strings in the module I have issues with passing the connection string data to the module.

Any advise as to the proper way to execute this?

Protect Programs From Termination, Reading, Or Modify
Does anyone know if its possable to make a program using Vb 6 that will Protect other applications from Termination, reading or Modify'ing. If so how can i do this?

Capturing Time In Case Of Abnormal Termination Of Pc
How to Capture the time in case of abnormal termination of pc or when the power goes away using vb6.0

SQL Server (& ADO) Stored Procedure Premature Termination
I am not really familiar with SQL Server stored procedures and I've got an
app that uses an ADO command object's "Execute" method to run one... The
procedure takes a long time to run but the CommandTimeout property in ADO is
set to 0 so it should work ok. However the stored procedure seems to be
fooling the ADO object into thinking that it has finished executing before
it really has (no error message... subsequent code just continues as if
procedure is finished!)... Does anyone know of any possible reasons for this
and how it can be overcome?

Copyright © 2005-08, All rights reserved