Monday, January 12, 2015

ShellExecute, Force open file to non-default application

As most of us know, ShellExecute() is a very useful tool to open a file on its external associated application.  When you issue this command:

Local lcFile
lcFile = Getfile('doc,docx')
If !Empty(m.lcFile)
      ShellExecute(0,'open',m.lcFile,'','',1)
Endif

Then that document file will be opened by MsWord or its counterpart like say on LibreOffice

Or if you do:

Local lcFile
lcFile = Getfile('xls,xlsx')
If !Empty(m.lcFile)
      ShellExecute(0,'open',m.lcFile,'','',1)
Endif

Or even:



Local lcFile
lcFile = Getfile('csv')
If !Empty(m.lcFile)
      ShellExecute(0,'open',m.lcFile,'','',1)
Endif

Most probably, it will be opened using Excel or its counterpart; whatever is set in the registry to be the default application associated to a file.

It also allows us to execute commands on the OS Shell such as open a folder to a specific location, prints directly a file to printer, etc.

See this:  http://www.ml-consult.co.uk/foxst-26.htm

In this blog though, we will focus on opening a file on an external application, but opening it not on its default associated external program, but based on our own choice.   What we will do is somewhat similar to right-clicking a file, choosing OPEN WITH, and forcefully using another program to open such file.

Going back to the last example above, we can say open a .csv file using a notepad instead of its default Excel program.  Or a .prg that is associated with VFP, to be opened using notepad as well.

The trick, you'll be surprised is very easy.  Okay, here we go:


* Declare it
Declare Integer ShellExecute In shell32.dll ;
      INTEGER hndWin, ;
      STRING cAction, ;
      STRING cFileName, ;
      STRING cParams, ;
      STRING cDir, ;
      INTEGER nShowWin

* Open an csv forcefully using Notepad
Local lcFile
lcFile = Getfile('csv')
If !Empty(m.lcFile)
      ShellExecute(0,'open','notepad.exe',["]+m.lcFile+["],'',1)
Endif


* Open an html forcefully using Word (normally it defaults to a browser)
Local lcFile
lcFile = Getfile('htm')
If !Empty(m.lcFile)
      ShellExecute(0,'open','winword.exe',["]+m.lcFile+["],'',1)
Endif

I think those two examples are enough.

Comparing the two approach side by side:

Standard approach
ShellExecute(0,'open',m.lcFile,'','',1)

Alternative approach
ShellExecute(0,'open','notepad.exe',["]+m.lcFile+["],'',1)

Notice that in the standard approach, the file to be opened is passed as the 3rd parameter and 4th parameter being empty?  On the Alternative approach, the 3rd parameter is the application we want to open and on the 4th parameter the file we wish to open.  Also, additional double quotes are added on both ends as enclosure to ensure that it will get the full path and file name correctly even if the path and filename will include spaces inbetween.


Cheers!

No comments:

Post a Comment