VB.Net Close window by title

apivb.netwindow

I'm searching a method to close a specific window by the title.

I tried with Process.GetProcessesByName; but not is working by this case particulary.

I'm searching a method with APIs or similar (Not in C#, I see several code but not work fine in vb.net)

Thanks!


UPDATE

Thanks for the reply. But I'm still have a problem with the solution that you describe me below.
I'm have an only process that's control two windows. Then, if I close (or kill) the Window #2, instantly close the first one (See the image).

By this reason I think in using an API method from the begging.

I'm only want close the second window.

Screenshot

Best Answer

Try using something like this. using Process.MainWindowTitle to get the Title Text and Process.CloseMainWindow to close down the UI, its a little more graceful than killing the Process.

Note: Contains does a case-sensitive search

Imports System.Diagnostics
Module Module1

    Sub Main()
        Dim myProcesses() As Process = Process.GetProcesses

        For Each p As Process In myProcesses
            If p.MainWindowTitle.Contains("Notepad") Then
                p.CloseMainWindow()
            End If
        Next

    End Sub

End Module

As far as Win API functions try something like this. Be aware if you close the parent window you will close the children also.

Module Module1
    Private Declare Auto Function FindWindowEx Lib "user32" (ByVal parentHandle As Integer, _
                                               ByVal childAfter As Integer, _
                                               ByVal lclassName As String, _
                                               ByVal windowTitle As String) As Integer

    Private Declare Auto Function PostMessage Lib "user32" (ByVal hwnd As Integer, _
                                                            ByVal message As UInteger, _
                                                            ByVal wParam As Integer, _
                                                            ByVal lParam As Integer) As Boolean

    Dim WM_QUIT As UInteger = &H12
    Dim WM_CLOSE As UInteger = &H10


    Sub Main()
        Dim handle As Integer = FindWindowEx(0, 0, Nothing, "YourFormsTitle")
        PostMessage(handle, WM_CLOSE, 0, 0)
    End Sub

End Module
Related Topic