2

I am using these libraries to find a window and set it's handle to a new handle, like a tab in my program. However, I am having a difficult time releasing the program back to the desktop. Once I close my main application, the window that was captured also closes. Could someone give me a hand please? thank you!

The library :

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

Here is how I would capture a running application, like notepad for example into the active tab in my program :

SetParent(FindWindow(vbNullString, "Untitled - Notepad"), TabControl1.SelectedTab.Handle)

This works fine when capturing the window into my tabpage, but how would I remove that window from my tabpage back onto the desktop?

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75
The Newbie
  • 379
  • 4
  • 18
  • 3
    What you are trying to do is not supported: [Is it legal to have a cross-process parent/child or owner/owned window relationship?](https://blogs.msdn.microsoft.com/oldnewthing/20130412-00/?p=4683) – IInspectable Jul 14 '18 at 11:12

1 Answers1

4

Per the documentation:

SetParent function

Parameters

(...)

hWndNewParent [in, optional]

Type: HWND

A handle to the new parent window. If this parameter is NULL, the desktop window becomes the new parent window. (...)

So all you need to do is call SetParent() again with the second parameter set to Nothing.

'Class-level variable (so that you can reference the window later on again).
Dim NotepadHandle As IntPtr
'Adding it into your application.
NotepadHandle = FindWindow(Nothing, "Untitled - Notepad")
SetParent(NotepadHandle, TabControl1.SelectedTab.Handle)
'Removing it from your application.
SetParent(NotepadHandle, Nothing)

IMPORTANT: Use this with caution! Changing the parent of a window belonging to another process (or simply another thread, even one in your own application) may cause issues, especially when that window is moved from being a top-level window (that is, a standalone window without a parent other than the desktop) to a child window.

If the application handling the window wasn't designed to support this it can cause all kinds of problems, and you can never really be certain what might happen because it all depends on how the application was coded and what it might decide or be instructed to do.

I recommend reading the link that IInspectable shared. It explains the situation a little more in detail and helps give a perspective on it.

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75