尝试从我从VB6运行的.NET可执行文件中获取错误代码

时间:2011-03-28 14:50:11

标签: api vb6 shellexecute

我使用ShellExecute API调用从VB6执行.NET控制台应用程序:

ExitCode = ShellExecute(Me.hWnd, "open", GetAppPath & "\SQL Utilities\" & "DocXferClient.exe", strFlags, vbNull, SW_HIDE)

在.NET应用程序(DocXFerClient)中,我发送尝试使用Environment.ExitCode返回“错误代码”:

Sub Main()
    BuildConnectionObject()
    ProcessRequest()

    Environment.ExitCode = 55 
End Sub

但是,无论我尝试返回的错误代码(在本例中为“55”),VB6中的ExitCode始终为“42”。我在VB6端,.NET端或两者都做错了吗?

2 个答案:

答案 0 :(得分:4)

ShellExecute不会返回退出代码。它会促使成功(值大于32)或失败(32或更少)。可以通过阅读the documentation或观察ShellExecute在流程退出之前返回其值的事实来解决这个问题。

强制性的Raymond Chen链接:What can I do with the HINSTANCE returned by the ShellExecute function?


要获取退出代码,请使用GetExitCodeProcess

要获取流程处理,请使用CreateProcess而不是ShellExecute运行您的应用。

不要忘记在它返回的进程和线程句柄上调用CloseHandle

答案 1 :(得分:0)

对于那些在我们的高级时期仍然受到VB6影响的人,我想发布一个大部分完整的例子。以下站点提供的代码非常棒:http://vbnet.mvps.org/index.html?code/faq/waitforsingleobject2.htm,但是您必须将两个示例放在一起以获得一个工作位,它将等待外壳应用退出而不进入CPU密集型循环并获得正确的退出代码。

Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" (ByVal hProcess As Long, lpExitCode As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Const SYNCHRONIZE = &H100000
Private Const WAIT_INFINITE = -1&
Private Const PROCESS_QUERY_INFORMATION = &H400

ProcessId = Shell("D:\iwCode\dev\proj\appmanager\MoveIniFileUtil\bin\Debug\MoveIniFileUtil.exe 5", vbNormalFocus)
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or SYNCHRONIZE, True, ProcessId)
dummyRet = WaitForSingleObject(hProcess, WAIT_INFINITE)
GetExitCodeProcess hProcess, exitCode
CloseHandle hProcess
MsgBox exitCode

这里不重要的一点是,你必须使用SYNCHRONIZE和PROCESS_QUERY_INFORMATION标志调用OpenProcess函数或者一起调用以使其工作。