Windows - Eseguire Un Programma Nella Shell E Attendere Che Sia Terminato.




Windows # Eseguire un programma nella Shell e attendere che sia terminato.
Spesso capita di dover eseguire un programma esterno dalla nostra applicazione VB, mediante una Shell, e dover attendere che sia terminato prima di restituire il focus all'applicazione:
'Inserire costanti e funzioni nelle dichiarazioni generali di un Form1:

Private Type STARTUPINFO
cbAs Long
lpReservedAs String
lpDesktopAs String
lpTitleAs String
dwXAs Long
dwYAs Long
dwXSizeAs Long
dwYSizeAs Long
dwXCountCharsAs Long
dwYCountCharsAs Long
dwFillAttributeAs Long
dwFlagsAs Long
wShowWindowAs Integer
cbReserved2As Integer
lpReserved2As Long
hStdInputAs Long
hStdOutputAs Long
hStdErrorAs Long
End Type
Private Type PROCESS_INFORMATION
hProcessAs Long
hThreadAs Long
dwProcessIDAs Long
dwThreadIDAs Long
End Type
Private Declare Function WaitForSingleObject Lib "kernel32" _
(ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function CreateProcessA Lib "kernel32" (ByVal _
lpApplicationName As Long, ByVal lpCommandLine As String, ByVal _
lpProcessAttributes As Long, ByVal lpThreadAttributes As Long, _
ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, _
ByVal lpEnvironment As Long, ByVal lpCurrentDirectory As Long, _
lpStartupInfo As STARTUPINFO, lpProcessInformation As _
PROCESS_INFORMATION) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal _
hObject As Long) As Long
Private Const NORMAL_PRIORITY_CLASS = &H20&
Private Const INFINITE = -1&
'Creare la seguente routine:

Public Sub ExecCmd(cmdline As String)
Dim proc As PROCESS_INFORMATION
Dim start As STARTUPINFO
'Inizializza la struttura STARTUPINFO:

start.cb = Len(start)
'Esegue il programma nella Shell:

ret& = CreateProcessA(0&, cmdline, 0&, 0&, 1&, _
NORMAL_PRIORITY_CLASS, 0&, 0&, start, proc)
'Attende che il programma nella Shell termini:

ret& = WaitForSingleObject(proc.hProcess, INFINITE)
ret& = CloseHandle(proc.hProcess)
End Sub

'Aggiungere il seguente codice nell'evento Form_Click() del Form1:

Sub Form_Click ()
ExecCmd "notepad.exe"
MsgBox "Process Finished"
End Sub

Premere F5 per eseguire l'applicazione e cliccare sul Form1. A questo punto il Notepad viene eseguito nella Shell.
Notare che l'istruzione MsgBox, che segue il lancio della Shell, non viene eseguita in quanto bloccata dalla funzione WaitForSingleObject().
Il MsgBox non apparira' finche' l'utente non chiudera' il Notepad.










( windowseseguireunprogrammanellashelleattenderechesiaterminato.html )- by Paolo Puglisi - Modifica del 17/12/2023