Search code examples
vb.nethwnd

How to close embedded window that was embedded using window handle?


So I have a method I am using to which I can integrate powerpoint into a panel. I use the FindWindow and SetParent functions to achieve this:

Dim proc as integer

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As Long) As Long
Private Declare Function SetParent Lib "user32" Alias "SetParent" (ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As Integer

Public Sub embed_Window()
    Do Until proc <> 0
        proc = FindWindow(vbNullString, window_name)
    Loop

    SetParent(proc, Panel1.Handle)

End Sub

This part works fine for embedding another window into my panel control. My question is, how can I close the window that is now in my panel? I can no longer use the FindWindow method as it is not a window in the task bar anymore.


Solution

  • In order to close an opened window you need to use PostMessage:

    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
    
    Public Const WM_CLOSE = &H10
    
    Public Sub CloseWindow()
     PostMessage(proc, WM_CLOSE, 0, 0)
    End Sub