Search code examples
delphidelphi-xe6delphi-xe7

Run a Terminal Command with Delphi XE7 FMX


How can I run a terminal command via Delphi xe6-7 OSX application ? I am wanting to run a script that returns all track names from iTunes playlist for example.

I see for VCL and WINDOWS I can run a ShellExecute() function, but I can't seem to find the equivalent for OSX in FMX


Solution

  • ShellExecute is a Windows OS function, not a VCL function. For reasons I am unsure of, BIBCE (Borland/Inprise/Borland/CodeGear/Embarcadero) never bothered to implement a function to launch a command in VCL/FMX, although many other cross-platform tools (Qt, Python, even FreePascal) have this. As Stephen Ball related in a blog post, if your app is cross-platform you'll need to use IFDEFs and the native function for each platform. :-(

    While I don't have access to OS X to test it on, Embarcadero's Ball gave the following code to illustrate launching a file on Windows and OS X, using "_system" for OS X:

    unit FileLauncher;
    
    interface
    
    uses
    {$IFDEF MSWINDOWS}
    Winapi.ShellAPI, Winapi.Windows;
    {$ENDIF MSWINDOWS}
    {$IFDEF MACOS}
    Posix.Stdlib;
    {$ENDIF MACOS}
    
    type
    TFileLauncher = class
    class procedure Open(FilePath: string);
    end;
    
    implementation
    
    class procedure TFileLauncher.Open(const FilePath: string);
    begin
    {$IFDEF MSWINDOWS}
    ShellExecute(0, 'OPEN', PChar(FilePath), '', '', SW_SHOWNORMAL);
    {$ENDIF MSWINDOWS}
    
    {$IFDEF MACOS}
    _system(PAnsiChar('open ' + '"' + AnsiString(FilePath) + '"'));
    {$ENDIF MACOS}
    end;