Library code snippets

Terminating Programs

This is how to end program like calculator or winword etc.
Put all the code in a new project with Command1 and Command2

It will start the calculator, then close it.

Option Explicit

     Private Declare Function WaitForSingleObject Lib "kernel32" _
        (ByVal hHandle As Long, _
        ByVal dwMilliseconds As Long) As Long

     Private Declare Function FindWindow Lib "user32" _
        Alias "FindWindowA" _
        (ByVal lpClassName As String, _
        ByVal lpWindowName As String) As Long

     Private Declare Function PostMessage Lib "user32" _
        Alias "PostMessageA" _
        (ByVal hwnd As Long, _
        ByVal wMsg As Long, _
        ByVal wParam As Long, _
        ByVal lParam As Long) As Long

     Private Declare Function IsWindow Lib "user32" _
        (ByVal hwnd As Long) As Long

     'Constants used by the API functions
     Const WM_CLOSE = &H10
     Const INFINITE = &HFFFFFFFF

     Private Sub Form_Load()
        Command1.Caption = "Start the Calculator"
        Command2.Caption = "Close the Calculator"
     End Sub

     Private Sub Command1_Click()
     'Starts the Windows Calculator
        Shell "calc.exe", vbNormalNoFocus
     End Sub

     Private Sub Command2_Click()
     'Closes the Windows Calculator
        Dim hWindow As Long
        Dim lngResult As Long
        Dim lngReturnValue As Long

        hWindow = FindWindow(vbNullString, "Calculator")
        lngReturnValue = PostMessage(hWindow, WM_CLOSE, vbNull, vbNull)
        lngResult = WaitForSingleObject(hWindow, INFINITE)

        'Does the handle still exist?
        DoEvents
        hWindow = FindWindow(vbNullString, "Calculator")
        If IsWindow(hWindow) = 1 Then
           'The handle still exists. Use the TerminateProcess function
           'to close all related processes to this handle.
           MsgBox "Handle still exists."
        Else
           'Handle does not exist.
           MsgBox "Program closed."
        End If
     End Sub

Comments

  1. 08 Jan 2009 at 18:27
    If you use this in Vb.Net, change the Long's to Integers on the API declarations.
  2. 14 Jul 2005 at 16:19
    what command or how to open other execute file like any program like winzip or something else?ok thanx
  3. 01 Jan 1999 at 00:00

    This thread is for discussions of Terminating Programs.

Leave a comment

Sign in or Join us (it's free).

Kym Manson Till the Roof comes off Till the Lights go out Till my Legs give out Can't shut my mouth I will not fall, my Wisdoms all.

Related discussion

Related podcasts

  • Christian Beauclair

    14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...

We'd love to hear what you think! Submit ideas or give us feedback