无法 运行 我自己创建的 exe inside parrent form (vb.net)

Unable to run my own created exe inside parrent form (vb.net)

我已经能够 运行 使用以下代码的外部程序。

Imports System.Runtime.InteropServices

Public Class Form1
    <DllImport("user32.dll")> Public Shared Function SetParent(ByVal hwndChild As IntPtr, ByVal hwndNewParent As IntPtr) As Integer

    End Function


Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    Dim PRO As Process = New Process
    PRO.StartInfo.FileName = ("notepad.exe")
    PRO.Start()
    Do Until PRO.WaitForInputIdle = True
        'Nothing
    Loop
    SetParent(PRO.MainWindowHandle, Me.Handle)
    PRO.Dispose()
End Sub

这很好用.....(对于记事本来说)

但是,如果我为自己的 vb.net 应用程序切换记事本,它无法在表单内启动该应用程序,而是 运行 在表单外启动它。我认为我尝试启动的应用程序可能有一些东西,所以我创建了一个新的应用程序,里面什么都没有(尽可能地裸露)和 运行 而不是记事本,但它也失败了在其“父”表单内启动,但它也在“父”表单之外触发 insted?

有人可以帮我解决这个问题吗?

您只需要稍等片刻即可填充 MainWindowHandle 属性。

这里有一个可以做到的拼凑:

Private Async Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    Dim PRO As Process = New Process
    PRO.StartInfo.FileName = ("C:\Users\mikes\Desktop\temp.exe")
    PRO.Start()
    Await Task.Run(Sub()
                       PRO.WaitForInputIdle()
                       While PRO.MainWindowHandle.Equals(IntPtr.Zero)
                           Threading.Thread.Sleep(10)
                       End While
                   End Sub)

    SetParent(PRO.MainWindowHandle, Me.Handle)
End Sub

如果您想要 10 秒的故障安全并捕获异常,那么您可以将其更改为:

Private Async Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    Try
        Dim PRO As Process = New Process
        PRO.StartInfo.FileName = ("C:\Users\mikes\Desktop\temp.exe")
        PRO.Start()
        Await Task.Run(Sub()
                           Dim timeout As DateTime = DateTime.Now.AddSeconds(10)
                           While timeout > DateTime.Now AndAlso PRO.MainWindowHandle.Equals(IntPtr.Zero)
                               Threading.Thread.Sleep(10)
                           End While
                       End Sub)

        If (Not PRO.MainWindowHandle.Equals(IntPtr.Zero)) Then
            SetParent(PRO.MainWindowHandle, Me.Handle)
        Else
            MessageBox.Show("Timed out waiting for main window handle.", "Failed to Launch External Application")
        End If
    Catch ex As Exception
        MessageBox.Show(ex.ToString, "Failed to Launch External Application")
    End Try
End Sub