How does one relaunch Finder programmatically?

末鹿安然 提交于 2019-12-09 13:09:23

问题


If I OPTION + RIGHT CLICK 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.


回答1:


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];



回答2:


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.




回答3:


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




回答4:


Killing Finder with killall Finder works since the system will automatically relaunch it.

[[NSTask launchedTaskWithLaunchPath:@"/usr/bin/killall" 
    arguments:[NSArray arrayWithObjects:@"Finder", nil]] waitUntilExit];


来源:https://stackoverflow.com/questions/1462425/how-does-one-relaunch-finder-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!