9

I've got a C++ app that I'm porting from Win32 to OSX. I'd like to be able to launch arbitrary files as if the user opened them. This is easy on windows using ShellExecute. How do I accomplish the same thing on the Mac?

Thanks!

Naaff
  • 8,961
  • 3
  • 35
  • 42
twk
  • 15,310
  • 21
  • 68
  • 95

3 Answers3

15

You can call system(); in any C++ application. On OSX, you can use the open command to launch things as if they were clicked on.

From the documentation for open:

The open command opens a file (or a directory or URL), just as if you had double-clicked the file's icon. If no application name is specified, the default application as determined via LaunchServices is used to open the specified files.

All together, it would look like:

string command = "open " + filePath;
system(command.c_str());
e.James
  • 109,080
  • 38
  • 170
  • 208
  • I think the windows equivalent is `"start " + filePath;` – MSalters May 14 '09 at 08:27
  • But on Windows we not needed full path, if application installed and added to windows PATH. For example: ShellExecute(0, L"open", L"Filename.exe", 0, 0, SW_SHOW); How I can do the same on Mac? – woland May 13 '20 at 13:09
9

Another suggestion if you're working with cocoa:

[[NSWorkspace sharedWorkspace] openFile:@"pathToFile"];

There are other similar methods in NSWorkspace as well. For example to open an application or a URL:

[[NSWorkspace sharedWorkspace] launchApplication:@"pathToApplication"];
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"URL"]];

Working through [NSWorkspace sharedWorkspace] can give you a bit more control than the standard C system() call.

Edit: Note that you can use Objective-C++ to mix C++ code with Objective-C code and thereby call cocoa methods.

0xced
  • 21,773
  • 10
  • 89
  • 238
Naaff
  • 8,961
  • 3
  • 35
  • 42
0

You can simply use the system(); function. For example, say you wanted to put your dock into the corner of the screen.

You can simply put:

system(defaults write com.apple.dock pinning -string end);
sleep(1f);
system(killall Dock);

It's that easy. Hope I helped :)

Asphyxia
  • 1
  • 1