无法在parrent表单中运行我自己创建的exe(vb.net)
Posted
技术标签:
【中文标题】无法在parrent表单中运行我自己创建的exe(vb.net)【英文标题】:Unable to run my own created exe inside parrent form (vb.net) 【发布时间】:2020-11-06 13:43:29 【问题描述】:我已经能够使用以下代码运行外部程序。
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 应用程序切换记事本,它将无法在表单内启动该应用程序,而是在表单外运行它。我认为我尝试启动的应用程序可能有一些东西,所以我创建了一个没有任何内容的新应用程序(尽可能裸露)并运行它而不是记事本,但它也无法在其“父”表单,而是在“父”表单之外触发?
有人可以帮我解决这个问题吗?
【问题讨论】:
【参考方案1】:您只需稍等片刻即可填充 MainWindowHandle
属性。
这是一个可以做到的kludge:
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
【讨论】:
大约 15 分钟前我认为我不得不等待更长的时间,并在思考如何才能做到这一点,这个解决方案给我带来了正确的方向,谢谢以上是关于无法在parrent表单中运行我自己创建的exe(vb.net)的主要内容,如果未能解决你的问题,请参考以下文章
CreateProcess 无法运行 sfc.exe ?为啥
Vs2019 无法运行 NUnit 测试 - 'testhost.x86.exe' 的问题