VB.NET在继续之前等待DOS shell程序终止 - 不起作用

时间:2014-04-07 13:18:36

标签: vb.net shell process

我正在VS2010上构建一个Windows窗体应用程序,通过它我需要执行一个3d派对DOS shell程序(OpenSees.exe),在其中打开一个源文件并执行分析。在此之后,创建了一些输出文件,我需要在我的VB.NET应用程序中再次阅读。 问题是OpenSees中的分析可能需要很长时间,因此VB代码必须等待它才能继续进行。

为此,我试过了两个" ShellandWait" sub with" WaitForSingleObject"功能和"流程类"选项,但两者都不起作用。 我的DOS shell程序初始化,但它几乎立即关闭,不让分析完成并创建所需的输出。

以下是我使用的代码段: 第一次尝试:ShellandWait

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 CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long


Private Sub ShellAndWait(ByVal program_name As String, _
                         Optional ByVal window_style As AppWinStyle = vbNormalFocus, _
                         Optional ByVal max_wait_seconds As Long = 0)
    Dim lngProcessId As Long
    Dim lngProcessHandle As Long
    Dim datStartTime As Date
    Const WAIT_TIMEOUT = &H102
    Const SYNCHRONIZE As Long = &H100000
    Const INFINITE As Long = &HFFFFFFFF

    ' Start the program.
    On Error GoTo ShellError
    lngProcessId = Shell(program_name, window_style)
    On Error GoTo 0
    Threading.Thread.Sleep(1500)
    'System.Windows.Forms.Application.DoEvents()

    SendKeys.Send("source " & filename & ".tcl")
    SendKeys.Send("{ENTER}")

    ' Wait for the program to finish.
    ' Get the process handle.
    lngProcessHandle = OpenProcess(SYNCHRONIZE, 0, lngProcessId)
    If lngProcessHandle <> 0 Then
        datStartTime = Now
        Do
            If WaitForSingleObject(lngProcessHandle, 250) <> WAIT_TIMEOUT Then
                Exit Do
            End If
            'DoEvents()
            If max_wait_seconds > 0 Then
                If DateDiff("s", datStartTime, Now) > max_wait_seconds Then Exit Do
            End If
        Loop
        CloseHandle(lngProcessHandle)
    End If
    Exit Sub

  ShellError:
  End Sub
  ...
  ShellAndWait("OpenSees.exe", , 3)

第二次尝试:ProcessStart

Dim p As New Process
Dim psi As New ProcessStartInfo("OpenSees.exe", "source " & filename & ".tcl")
p.StartInfo = psi
p.Start()

p.WaitForExit()

我不明白为什么这不起作用。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

试试这个:

Shell("OpenSees.exe <arguments>",, True)