Solved

Executing .bat file through vb

Posted on 2002-07-17
20
776 Views
Last Modified: 2008-02-01
I want to execute .bat file on button click.Presently I am using shell function.But before complete execution of .bat file it is exiting from that file.So full execution is not happenning.

my code is

RetVal = Shell("C:\BlueGenet\test.bat", 1)
MsgBox RetVal


before complete execution of .bat file it is showing msgbox with number and exits from that file.

any suggetion.

0
Comment
Question by:a_padwal
  • 7
  • 3
  • 3
  • +6
20 Comments
 
LVL 2

Expert Comment

by:yongyih
Comment Utility
This is from MSDN Library.

Note   By default, the Shell function runs other programs asynchronously. This means that a program started with Shell might not finish executing before the statements following the Shell function are executed.

So, if u want to finish the bat file first before continue, you have to find another way.

Good Luck.
0
 
LVL 2

Expert Comment

by:yongyih
Comment Utility
How about this..

' AppActivate can also use the return value of the Shell function.
MyAppID = Shell("C:\WORD\WINWORD.EXE", 1)   ' Run Microsoft Word.
AppActivate MyAppID, true   ' Activate Microsoft    ' Word.

0
 

Expert Comment

by:Amitabh
Comment Utility
in shell function you call an exe or a batch file and then proceed to next line...

us this code. it is using a function shellandwait

=====================================================Option Explicit

Private Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long

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

Private Const STATUS_PENDING = &H103&
Private Const PROCESS_QUERY_INFORMATION = &H400


Public Function Shellandwait(ExeFullPath As String, _
Optional TimeOutValue As Long = 0) As Boolean
   
    Dim lInst As Long
    Dim lStart As Long
    Dim lTimeToQuit As Long
    Dim sExeName As String
    Dim lProcessId As Long
    Dim lExitCode As Long
    Dim bPastMidnight As Boolean
   
    On Error GoTo ErrorHandler

    lStart = CLng(Timer)
    sExeName = ExeFullPath

    'Deal with timeout being reset at Midnight
    If TimeOutValue > 0 Then
        If lStart + TimeOutValue < 86400 Then
            lTimeToQuit = lStart + TimeOutValue
        Else
            lTimeToQuit = (lStart - 86400) + TimeOutValue
            bPastMidnight = True
        End If
    End If

    lInst = Shell(sExeName, vbMinimizedNoFocus)
   
lProcessId = OpenProcess(PROCESS_QUERY_INFORMATION, False, lInst)

    Do
        Call GetExitCodeProcess(lProcessId, lExitCode)
        DoEvents
        If TimeOutValue And Timer > lTimeToQuit Then
            If bPastMidnight Then
                 If Timer < lStart Then Exit Do
            Else
                 Exit Do
            End If
    End If
    Loop While lExitCode = STATUS_PENDING
   
    Shellandwait = True
   Exit Function
   
ErrorHandler:
Shellandwait = False
Exit Function
End Function



0
 
LVL 2

Expert Comment

by:yongyih
Comment Utility
Sorry, u can use Shell function.

Try this..

Private Sub Command1_Click()
  MyAppID = Shell("C:\windows\calc.EXE", 1)   ' Run
  AppActivate MyAppID, True  
  MsgBox "Run..."
End Sub


Hope this can help.  Thanks first. ^_^
0
 

Expert Comment

by:Amitabh
Comment Utility
i am not contradicting yongyih's ans. you can very well do it this way using AppActivate.

but here is a code which is also doing it in different way.
In shell you don't wait for the execution of the exe/bat or the batch file and u immediately move to the next line. if you want to wait till the called exe/bat is executed, u can use the shellandwait function.
just copy paste the code sent above in a module and use
shellandwait function.
hope this gives you another way to solve the problem.

-A. Pandey
0
 

Author Comment

by:a_padwal
Comment Utility
amitabh
still it is exiting after using using your function.I had given wait of 1000.
yongyih
it is showing invalid App at  "AppActivate MyAppID, True"  
 
I am firing two commands from .bat file.
is there any other way to fire commands through vb.

0
 

Expert Comment

by:Amitabh
Comment Utility
try 0 instead of 1000

and is it possible for u to tell us what is this bat file doing. a bit of code ....i mean
0
 
LVL 3

Expert Comment

by:Rem
Comment Utility
I agree with Amitabh .
What is this bat file doing what cannot be done directly through the UI?
0
 
LVL 3

Expert Comment

by:Bahnass
Comment Utility
Using Api's   U can Use shellexecute to execute some exe

then WaitForSingleObject to wait for it to finish

if this is usefull I can send code

(U can also see it in PAQ or   www.allapi.net
0
 

Expert Comment

by:Amitabh
Comment Utility
giving u another code which uses waitforsingleobject API as suggested by bahnass
just copy paste it in a *.bas (module) and use the function.

======================================================

Option Explicit

Const INFINITE = &HFFFF
Const STARTF_USESHOWWINDOW = &H1
Public Enum enSW 'Private
    SW_HIDE = 0
    SW_NORMAL = 1
    SW_MAXIMIZE = 3
    SW_MINIMIZE = 6
End Enum
Public Type PROCESS_INFORMATION
    hProcess As Long
    hThread As Long
    dwProcessId As Long
    dwThreadId As Long
End Type
Public Type STARTUPINFO
    cb As Long
    lpReserved As String
    lpDesktop As String
    lpTitle As String
    dwX As Long
    dwY As Long
    dwXSize As Long
    dwYSize As Long
    dwXCountChars As Long
    dwYCountChars As Long
    dwFillAttribute As Long
    dwFlags As Long
    wShowWindow As Integer
    cbReserved2 As Integer
    lpReserved2 As Byte
    hStdInput As Long
    hStdOutput As Long
    hStdError As Long
End Type
Public Type SECURITY_ATTRIBUTES
    nLength As Long
    lpSecurityDescriptor As Long
    bInheritHandle As Long
End Type
Public Enum enPriority_Class
    NORMAL_PRIORITY_CLASS = &H20
    IDLE_PRIORITY_CLASS = &H40
    HIGH_PRIORITY_CLASS = &H80
End Enum

Private Declare Function CreateProcess Lib "kernel32" Alias "CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, lpProcessAttributes As SECURITY_ATTRIBUTES, lpThreadAttributes As SECURITY_ATTRIBUTES, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDriectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long

Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long


Public Function SuperShell(ByVal app As String, ByVal WorkDir As String, dwMilliseconds As Long, ByVal start_size As enSW, ByVal Priority_Class As enPriority_Class) As Boolean
    Dim pclass As Long
    Dim sinfo As STARTUPINFO
    Dim pinfo As PROCESS_INFORMATION
    'Not used, but needed
    Dim sec1 As SECURITY_ATTRIBUTES
    Dim sec2 As SECURITY_ATTRIBUTES
    'Set the structure size
    sec1.nLength = Len(sec1)
    sec2.nLength = Len(sec2)
    sinfo.cb = Len(sinfo)
    'Set the flags
    sinfo.dwFlags = STARTF_USESHOWWINDOW
    'Set the window's startup position
    sinfo.wShowWindow = start_size
    'Set the priority class
    pclass = Priority_Class
    'Start the program
    If CreateProcess(vbNullString, app, sec1, sec2, False, pclass, _
    0&, WorkDir, sinfo, pinfo) Then
        'Wait
        WaitForSingleObject pinfo.hProcess, INFINITE 'dwMilliseconds
        SuperShell = True
    Else
        SuperShell = False
    End If
End Function



===========================================================
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Expert Comment

by:Amitabh
Comment Utility
to make it more easy for you sending you a function which calls supershell. just paste it too in the module and u can call this function.

=========================================================
Public Function synchshell(ByVal app As String, ByVal waittime As wait, ByVal start_size As AP_enSW, ByVal Priority_Class As AP_Priority_Class) As Boolean
    Dim p_retshell As Boolean
    p_retshell = SuperShell(app, Left$(app, Len(app) - Len(Dir$(app))), waittime, start_size, Priority_Class)
    synchshell = p_retshell
End Function
0
 
LVL 27

Expert Comment

by:Ark
Comment Utility
Hi

Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
RetVal oShell.Run(("C:\BlueGenet\test.bat", 1, True)
Set oShell = Nothing
MsgBox RetVal
'RetVal contain return value:
'0 if successfull
'Error code if error occure
'or ERRORLEVEL value from *.bat file.

Cheers
0
 

Expert Comment

by:Amitabh
Comment Utility
Now i think we have seen enough ways of calling an exe/bat file synchronously and all are right and working ways. so we need to see where actually you are held up. Also try 0 as the input time as i had written earlier instead of 1000 since 0 means indefinite waiting till the called exe/bat gets executed.

-A.Pandey
0
 

Author Comment

by:a_padwal
Comment Utility
Following are lines in bat file

set PATH=C:\jdk1.3.0_02\bin;%PATH%

java -cp  cl.jar Cl test11 10000 $admin$:0:2:gi:test

"C:\Documents and Settings\abc\Desktop\test\AutoTest\AutoTest.exe"

I want to execute .jar and .exe

.jar writes some value to database and after transfering data returns message whether transfermation is succesfull or not.
.exe checks whether all data transfer is done or not.

but before complition of .jar it shifts to .exe.

I have used supershell but it returns False.
0
 
LVL 16

Expert Comment

by:Richie_Simonetti
Comment Utility
hearing...
0
 

Expert Comment

by:Amitabh
Comment Utility
i think the execution of jar file not even starts and fails and then your code move to next line.

One possible scenario for which you can check.

you r calling ur exe/bat something like this
shell "c:\program files\my_proj\myexe"

In windows there is no barrier of 8.3 naming convention so our APP.Path becomes something like the above. It takes characters after program as a parameter and assumes program as some exe.

So put your exe/bat in C: drive and try to run the code

shell "c:\myexe"

May be this is the problem i am just guessing. becoz something that can be run from the command prompt shouldn't give any problem from the UI. Plus all the codes sent above like shellandwait and supershell and others are working ones.

cheers!!
0
 
LVL 16

Expert Comment

by:Richie_Simonetti
Comment Utility
i think you could add a line in your bat but i am not sure.
After calling jar execution add:
@IF ERRORLEVEL THEN PAUSE
set your Shell calling to vbnormal to see what happens, at least to debug.
0
 
LVL 16

Expert Comment

by:Richie_Simonetti
Comment Utility
i don't know if it is applicable here but take a look to this interesting article anyway:

http://www.vbdna.net/articles/comcallingjava.asp
0
 
LVL 49

Expert Comment

by:DanRollins
Comment Utility
Hi a_padwal,
It appears that you have forgotten this question. I will ask Community Support to close it unless you finalize it within 7 days. I will ask a Community Support Moderator to:

    Refund points and save as a 0-pt PAQ.
    *** Possible answer: Use START /WAIT command in the batch file

a_padwal, Please DO NOT accept this comment as an answer.
EXPERTS: Post a comment if you are certain that an expert deserves credit.  Explain why.
==========
DanRollins -- EE database cleanup volunteer
0
 
LVL 1

Accepted Solution

by:
Computer101 earned 0 total points
Comment Utility
Question placed in PAQ

Computer101
E-E Admin
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Introduction In a recent article (http://www.experts-exchange.com/A_7811-A-Better-Concatenate-Function.html) for the Excel community, I showed an improved version of the Excel Concatenate() function.  While writing that article I realized that no o…
Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now