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

You might also like...

Comments

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.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Perl - The only language that looks the same before and after RSA encryption.” - Keith Bostic