Tuesday, July 1, 2008

FoxPro To Run External Application

In Visual FoxPro, the best way to run an external application is by using the ShellExecute() API function.

For the complete explanation on the ShellExecute() function, please refer to this Foxite's article .

To make things easy, I put all the codes into a program PRG. Whenever I need to call an external application, I just run this procedure.

********************************************************************
* Program: runexapp.prg
* Purpose: Procedure to execute an external application, with parameters.
* Usahe : DO runexapp WITH <cApplication>, <cParameters>
********************************************************************

PARAMETERS In_App, In_Params

IF TYPE("In_Params") <> "C"
In_Params = ""
ENDIF

** Declare API function (only need to declare once in main.prg).
DECLARE INTEGER ShellExecute IN shell32.DLL ;
INTEGER hndWin, ;
STRING cAction, ;
STRING cFileName, ;
STRING cParams, ;
STRING cDir, ;
INTEGER nShowWin
**

cAction = "open"
cFileName = In_App
cParams = In_Params
cPath = ""

mRtn = ShellExecute(0,cAction,cFileName,cParams,cPath,1)

** Extra checking.
DO CASE
CASE mRtn = 2
mMsg = "Bad Association"
CASE mRtn = 29
mMsg = "Failure to load application"
CASE mRtn = 30
mMsg = "Application is busy"
CASE mRtn = 31
mMsg = "No application association"
OTHERWISE
mMsg = ""
ENDCASE

IF !EMPTY(mMsg)
MESSAGEBOX(mMsg,48,"Error")
ENDIF

CLEAR DLLS ShellExecute
**

To use the procedure, just put a single line in your program:
DO runexapp WITH 'c:\program\someapp.exe'
You can pass the optional parameters as the second arguments if needed.

If you find this post helpful, would you buy me a coffee?


6 comments:

  1. Very useful for me. Thank for putting it.

    ReplyDelete
  2. This does not run with spaces in either the folder or xls file name.

    Otherwise works great.

    Please send feedback if I am running it wrong.

    delislec2@netzero.net

    ReplyDelete
    Replies
    1. because if you put spaces in the In_App
      the shellExecute() assumes that the string after the space is the parameters to be passed on the APPLICATION / EXE :)

      Delete
    2. Putting the file name between quotes will do it:

      shellexecute('C:\Program Files\Sublime Text 3\sublime_text.exe',' "test x.html" ')


      Delete
  3. Thanks dear, very useful post at least for me.
    great work.
    thx again
    Aziz

    ReplyDelete
  4. This is very simplest way to avoid
    duplication of program work.

    Thank You.
    CDD

    ReplyDelete