We should not directly kill the process. We should properly close the main window of the application using CloseMainWindow().
Here is the proper way of terminating the application in VB.Net. The code below will request the application to close properly and will wait for 10 seconds. if the application is not closed in 10 seconds then it will kill the process.
As this is console application you cannot directly use the Application.DoEvents method. You need to add reference to System.Windows.Forms using Project > Add Reference and select System.Windows.Forms and hit OK.
Module modMain
Sub Main()
'How to call this function:
'This will return true if the process is terminated; and false if unable to terminate the process
Console.WriteLine(TerminateProcess("firefox")) 'This will terminate the firefox application
End Sub
Public Function TerminateProcess(ByVal sProcessName As String) As Boolean
Dim lTimer As Long
Try
For Each oProc As Process In Process.GetProcessesByName(sProcessName)
'To ask the process to exit.
oProc.CloseMainWindow()
lTimer = CLng(Microsoft.VisualBasic.Timer)
Do Until oProc.HasExited
System.Windows.Forms.Application.DoEvents()
If Microsoft.VisualBasic.Timer - lTimer > 10 Then
oProc.Kill()
End If
Loop
Next oProc
Return True
Catch ex As Exception
Console.WriteLine("Error 003: Unable to close the application " & sProcessName)
Return False
End Try
End Function
End ModuleProject Type: Console
Language: VB.Net
Tested with: VS 2008
Incoming search terms:
- terminate the application
- c# stop process properly
- visual basic closemainwindow
- vb net shutdown windows by terminating processes
- vb net kill process correctly
- vb 2008 closemainwindow
- termination of a vb net windows application process
- terminated program vb net
- process for terminating blogger
- kill process properly
