Attribute VB_Name = "Module2"
Option Explicit



'Declaraciónes apis

' Lista las ventanas
Declare Function EnumWindows Lib "user32" ( _
                 ByVal wndenmprc As Long, _
                 ByVal lParam As Long) As Long

'Recupera el texto de la misma
Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" ( _
                 ByVal hwnd As Long, _
                 ByVal lpString As String, _
                 ByVal cch As Long) As Long

'Para finalizar dicha ventana
Declare Function SendMessage Lib "user32" Alias "SendMessageA" ( _
                 ByVal hwnd As Long, _
                 ByVal wMsg As Long, _
                 ByVal wParam As Long, _
                 lParam As Any) As Long


'Constantes para usar con SendMessage
Const WM_SYSCOMMAND = &H112
Const SC_CLOSE = &HF060&
Public vCantProg As Integer

'Almacena el caption de la vaentana a cerrar
Private El_titulo As String

' Recibe el título parcial o igual de las ventanas a cerrar
Public Sub Cerrar_ventana(El_Caption As String)
    El_titulo = El_Caption
    Call EnumWindows(AddressOf EnumCallback, 0)
End Sub


' Función para recorrer las ventanas abiertas
Public Function EnumCallback(ByVal A_hwnd As Long, _
                ByVal param As Long) As Long

Dim buffer As String * 256
Dim Titulo_Win As String
Dim Size_buffer As Long

    'Retorna la cantidad de caracteres del título de la ventana actual
    Size_buffer = GetWindowText(A_hwnd, buffer, Len(buffer))
    'Elimina los espacios nulos de la cadena
    Titulo_Win = Left$(buffer, Size_buffer)
    
    'si se encuentra la cadena en el caption de la ventana se cierra
    If InStr(Titulo_Win, El_titulo) <> 0 Then
        If vCantProg = 0 Then
        Else
        ' Finaliza la ventana
        SendMessage A_hwnd, WM_SYSCOMMAND, SC_CLOSE, ByVal 0&
        End If
        vCantProg = vCantProg + 1
    End If

    ' Esto continúa enumerando las siguientes ventanas de windows
    EnumCallback = 1
End Function
 


