views:

508

answers:

3

If I ALT+RIGHTCLICK on the Finder icon, I get a "Relaunch" option in the context menu. I would like to programmatically relaunch finder, if at all possible. I'm sure there is a better way to do it than to just kill it and let it restart. Assume I have the proper authorization / permissions to do so already.

Additionally, I would like to restart spotlight as well.

A: 

'Relaunch' almost certainly just sends a kill signal to the Finder.

ceejayoz
+3  A: 

Finder is kept alive by the system, so you can just kill it and it will automatically relaunch. I use killall Finder to accomplish this.

Dave DeLong
Yeah, Explorer on Windows is similar, but randomly killing Explorer can lead to bad things; much better to shut it down cleanly.
jeffamaphone
+3  A: 

Send it a quit event using AppleScript, then send it an activate event:

//tell Finder to quit
NSAppleScript *restartFinder = [[NSAppleScript alloc] initWithSource:@"tell application \"Finder\" to quit"];
[restartFinder executeAndReturnError:nil];

EDIT: add a delay to make sure Finder is ready to receive an activate event. On my machine, sometimes it needs this delay, sometimes it doesn't:

//delay 1 second
restartFinder = [[NSAppleScript alloc] initWithSource:@"delay 1"];
[restartFinder executeAndReturnError:nil];

(...end EDIT)

//tell Finder to activate
restartFinder = [[NSAppleScript alloc] initWithSource:@"tell application \"Finder\" to activate"];
[restartFinder executeAndReturnError:nil];
Rob
aren't you doing the same thing twice???
Matt S.
You've got a memory leak. Plus, there's no need to activate Finder. It will restart automatically.
Dave DeLong
matt... the first script is 'quit', the second is 'activate'. The sample code is leaky for sure. Finder does not reactivate without being told in at least Snow Leopard. Not positive about prior OS, but I'm pretty sure a "truly" quit Finder stays quit.
Rob
The code's not leaky under GC, of course.
Barry Wark
This looks promising.
jeffamaphone
@Barry touché, but i think it will always feel wrong to see an alloc/init and no release...
Dave DeLong
You may need to put in a delay (or maybe an AppleScript try block) between the calls. If the Finder isn't done quitting yet, it probably can't be activated.
Rob
So, it doesn't seem like "tell application \"Finder\" to activate" is working for me.
jeffamaphone
Yeah, telling it to activate doesn't work on 10.5 or 10.6... how does one start Finder again?
jeffamaphone
I had to switch "activate" to "launch" and do it twice(?) but I got it working. If you have further advice, let me know.
jeffamaphone
I added some extra code above. What's happening is that the Finder cannot accept an activate event if it's still in the process of quitting cleanly. A 1 second delay always works perfectly on my setup. (With no delay, sometimes it would still activate.)
Rob