# Running applications from DelphiTM: Using ShellExecute (Part 1) {转贴}

## Running applications from DelphiTM: Using ShellExecute (Part 1)

Level: Newbie-Hacker
Author: The Baker
Date: 2002-04-19

Running or opening external programs or files, from DelphiTM applications, is often a necessary requirement. This article covers the ShellExecute Windows API function, revealing techniques for running external applications from your Delphi applications.

### Running applications from Delphi

There are a number of reasons why you might be interested in running external applications from your Delphi application. Often programs are segmented into a number of logical divisions to represent different components of a larger system. Some sub-system components might include:

• Main application

• Setup/Installer application

• System application (specifying system wide options)

• Application server application

• Reporting application

• an external third party application

As can be seen, there are a number of reasons why you might need to call an external application. Let's discuss how we can do this with the ShellExecute command.

### ShellExecute WinAPI

The ShellExecute API allows for the execution (or "running") of external applications. It also has a number of other uses, however these all involve performing operations on external files. The syntax for the ShellExecute WinAPI function is:

HINSTANCE ShellExecute(HWND hwnd,     LPCTSTR lpOperation,     LPCTSTR lpFile,     LPCTSTR lpParameters,     LPCTSTR lpDirectory,     INT nShowCmd);

The following is a description of the parameters for the ShellExecute function.

 Parameter Input/Output Description hwnd input Handle to the parent window: needed for error reporting. lpOperation input Pointer to a null-terminated string. This is the action to be performed (the "object verb") lpFile input Pointer to a null-terminated string that specifies the file or object to execute the specified verb on. lpParameters input Pointer to a null-terminated string that specifies the parameters to be passed to the application (if the lpFile is an application file). Otherwise, this should be NULL. lpDirectory input Pointer to a null-terminated string that specifies the default directory. nShowCmd input Flag determining how the application window will be displayed when it is opened.

The ShellExecute function will return an error code if the function fails. This can be retrieved using the GetLastError function. If the error code is greater than 32, then the function was successful. If it less than or equal to 32 then an error has occurred. For a complete listing of the error codes refer to the MSDN website (link provided in the further reading section).

The easiest way to interpret the error code is with the SysErrorMessage(GetLastError) function call. This will map the appropriate Windows error message returned by the GetLastError API function.

  if ShellExecute(Handle, 'print', PChar('c:/log.txt'), nil, nil, SW_SHOWNORMAL) <= 32 then    ShowMessage(SysErrorMessage(GetLastError));

### Operation Type

The ShellExecute function allows for operations to be executed on programs and application objects. In some cases, objects may not be able to respond to an operation type. For example, not all document types support the "print" verb. A list of the commonly supported verbs include:

 lpOperation Value Result Description edit Opens a document for editing in an editor. explore Explores the folder, using Windows Explorer, specified by the lpFile parameter. find Opens the Search form initiating a search starting from the directory specified in the lpFile parameter. open Opens the file, application or folder specified by the lpFile parameter. print Prints the document file specified by lpFile parameter. NULL More information below

If NULL is specified then different functionality will occur depending on the operating system version. The following is an extract from the MSDN ShellExecute document:

For systems prior to Microsoft?Windows?2000, the default verb is used if it is valid and available in the registry. If not, the "open" verb is used.
For Windows 2000 and later systems, the default verb is used if available. If not, the "open" verb is used. If neither verb is available, the system uses the first verb listed in the registry.

If I use the "open" verb on a .PAS file, nothing happens. If I use NULL instead, then the .PAS file will be opened in Delphi. The registry defines the application that is associated with the .PAS file.

### Show Command

The ShellExecute requires the nShowCmd type. This represents how the new window will be displayed when it is created via the ShellExecute call.

 nShowCmd Value Result Description SW_HIDE Hides the window and activates another window. SW_MAXIMIZE Maximizes the specified window. SW_MINIMIZE Minimizes the specified window and activates the next top-level window in the z-order. SW_RESTORE Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when restoring a minimized window. SW_SHOW Activates the window and displays it in its current size and position. SW_SHOWDEFAULT Sets the show state based on the SW_ flag specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application. An application should call ShowWindow with this flag to set the initial show state of its main window. SW_SHOWMAXIMIZED Activates the window and displays it as a maximized window. SW_SHOWMINIMIZED Activates the window and displays it as a minimized window. SW_SHOWMINNOACTIVE Displays the window as a minimized window. The active window remains active. SW_SHOWNA Displays the window in its current state. The active window remains active. SW_SHOWNOACTIVATE Activates and displays a window. Windows restores it to its original size and position. The active window remains active. SW_SHOWNORMAL Activates and displays a window. Windows restores it to its original size and position.

When you call an application for the first time you should call the SW_SHOWNORMAL flag.

### Using ShellExecute

The following is a list of ShellExecute uses. You will need to add the Windows and ShellAPI units to the uses clause.

Run an application called Demo.exe in "C:/apps" directory:

  ShellExecute(Handle,NIL,PChar('C:/apps/demo.exe'), nil,nil,SW_SHOWNORMAL);

Open a file (e.g. "log.txt"):

  ShellExecute(Handle,'open',PChar('c:/log.txt'), nil,nil,SW_SHOWNORMAL);

Play a music file (e.g. "ending.mp3"):

  ShellExecute(Handle,'play',PChar('c:/ending.mp3'), nil,nil,SW_SHOWNORMAL);

Print a log file (e.g. "log.txt"):

  ShellExecute(Handle,'print',PChar('c:/log.txt'), nil,nil,SW_SHOWNORMAL);

Open up Windows Explorer on C Drive (e.g. "c:"):

  ShellExecute(Handle,'explore',PChar('c:/'), nil,nil,SW_SHOWNORMAL);

Create a new email message with Outlook or Outlook express:

Procedure CreateEmail(Const EmailAddr, Subject, Body: String);var  ConcatEmailStr: String;Begin  ConcatEmailStr := EmailAddr + '?subject=' + Subject + '&body=' + Body;  ShellExecute(Handle,'open',PChar(ConcatEmailStr), nil, nil, SW_SHOWNORMAL);end;

### Conclusion

I hope this article has provided you with a greater insight into running applications from Delphi and the ShellExecute WinAPI function. In the next article I will discuss how to wait for an application to finish before resuming application execution.

For further information on the ShellExecute WinAPI function refer to the MSDN online library:

#### ShellExecuteEx打开、关闭exe

2015-05-15 17:07:48

#### 用ShellExecuteEx打开文件，文件夹

2008-11-17 09:57:00

#### ShellExecute()用法以及和system()的区别

2010-03-01 17:24:00

#### Process.start五种用法

2012-02-03 12:05:38

#### 怎样在一个项目中引用另一个项目的文件

2010-03-28 16:36:00

#### warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries f

2015-09-19 10:29:11

#### Using 'dlopen' in statically linked applications requires at runtime the shared libraries

2018-03-08 21:22:01

#### warning: Using 'getaddrinfo' in statically linked applications requires at runtime the shared librar

2017-11-24 09:52:30

#### mamp pro中mysql报错解决

2017-12-11 09:35:16

#### CVPR 2016-11-28

2016-12-05 11:57:32