After my article on Special Folders, a few people asked how to open a file in the default application.
For example, if I open a JPEG, whichever application is registered as the default app for JPEGs will execute. This is roughly analogous to ShellExecute in Windows.
The question was also asked about opening a URL in the default browser and also sending an email with the default mail application. These are closely related so I’ll cover them at the same time.
It’s actually pretty easy. I’ve got a TOpenDialog on a form, and the following code in a TButton.OnClick event:
procedure TForm2.Button1Click(Sender: TObject);
var
Workspace : NSWorkspace;
begin
if OpenDialog1.Execute then
begin
Label1.Text := OpenDialog1.FileName;
Workspace := TNSWorkspace.Create;
Workspace.openFile(NSSTR(Label1.Text));
end;
end;
Once we have the filename from the TOpenDialog, we create a NSWorkspace reference and use the openFile method, converting the filename string to a NSString on the way. NSWorkspace is defined in Macapi.Appkit and the NSSTR function to convert a String to a NSString is defined in Macapi.Foundation;
Opening a URL in a browser is slightly longer but not much:
procedure TForm2.Button3Click(Sender: TObject);
var
URL : NSURL;
Workspace : NSWorkspace;
begin
URL := TNSURL.Create;
URL.initWithString(NSSTR('http://www.malcolmgroves.com'));
Workspace := TNSWorkspace.Create;
Workspace.openURL(URL);
end;
Instead of the NSWorkspace.openFile method, we need to use openURL. This expects a NSURL as a parameter, so we construct that and load it up with the initWithString method, again converting our String to a NSString along the way. Executing that code causes Safari (on my machine) to open my website.
Opening a new mail and setting the To, Subject and Body is much the same, just down to the string we pass into our NSURL:
procedure TForm2.Button2Click(Sender: TObject);
var
URL : NSURL;
Workspace : NSWorkspace;
begin
URL := TNSURL.Create;
URL.initWithString(NSSTR('mailto:fred@flintstones.com?subject=Hello&body=Hello%20Fred'));
Workspace := TNSWorkspace.Create;
Workspace.openURL(URL);
end;
You can download the sample project from my delphi-samples repository on github.