PDA

View Full Version : Need help with API calls to close a CMD window early



Dr.K
06-12-2007, 07:18 AM
I'm just learning Windows API calls, so I need some help with this...
I'm currently using the "ShellandWait" code to call Shell commands (such as batch files, FTP .DAT, and so forth.)

What I want to do is close the running shell window prematurely, and return to the VBA code. I'm calling it "ShellAndWaitAndClose".

In my current application, I would use this to start an FTP download of a VERY large text file and stop it after a few seconds. This will allow me to read in a singl line of text and check the internal date stamp on the data, without FTPing the entire file.

'ShellandWait Sub

'This subroutine uses Windows API calls to force Excel to wait
'for the window opened by the Shell command to close before
'continuing to execute the VBA script.

'Windows API calls
Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long

Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, _
lpExitCode As Long) As Long

Public Const PROCESS_QUERY_INFORMATION = &H400
Public Const STILL_ACTIVE = &H103


Sub ShellAndWait(ByVal PathName As String, Optional WindowState)
Dim hProg As Long
Dim hProcess As Long, ExitCode As Long

'fill in the missing parameter and execute the program
If IsMissing(WindowState) Then WindowState = 1
hProg = Shell(PathName, WindowState)
'hProg is a "process ID under Win32. To get the process handle:
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, False, hProg)
Do
'populate Exitcode variable
GetExitCodeProcess hProcess, ExitCode
DoEvents
Loop While ExitCode = STILL_ACTIVE
End Sub



Googling around, I found some code snipits that look useful:
Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _
lParam As Any) As Long

Private Const WM_CLOSE = &H10


SendMessage app_hWnd, WM_CLOSE, 0, 0

However, I'm not sure how to put it all together. I'm continuing to tinker, but any advice would be greatly appreciated.