How to properly terminate the application by passing the process name

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 Module

Project Type: Console
Language: VB.Net
Tested with: VS 2008

Incoming search terms:

This entry was posted in System & API, VB.Net and tagged c#.net .Net, How to, How to terminate application, proper way of terminating the application, terminate application, VB.Net, vb.net code. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>