簡體   English   中英

如何重新啟動Finder應用程序

[英]How to relaunch finder application

我正在使用以下applescript重新啟動finder應用程序。

osascript -e "tell application \"Finder\"" -e "delay 1" -e "try" -e "quit" -e "delay 1" -e "activate" -e "end try" -e "end tell"  

但是有時此腳本不會重新啟動finder應用程序(僅退出finder應用程序)。 我在控制台中沒有任何錯誤。
http://www.cocoabuilder.com/archive/cocoa/113654-nsapplescript-buggy.html
有人可以幫我嗎?

如果您使用可可粉,這是做事的錯誤方法。 在可能的情況下,應始終使用本機API,而嘗試調用本身可構建並運行AppleScript的Shell腳本。 您的AppleScript等待一秒鍾,然后嘗試重新啟動,這是一個任意值。 您實際上應該在等待Finder退出。

相反,您應該使用NSRunningApplication類來管理此操作,方法是使用鍵值觀察來監視實例的terminated屬性,以便可以在終止該應用程序時重新啟動該應用程序:

//assume "finder" is an ivar of type NSRunningApplication
//it has to be a strong reference or it will be released before the observation method
//is called

- (void)relaunchFinder
{
    NSArray* apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.finder"];
    if([apps count])
    {
        finder = [apps objectAtIndex:0];
        [finder addObserver:self forKeyPath:@"isTerminated" options:0 context:@"QuitFinder"];
        [finder terminate];
    }

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == @"QuitFinder")
    {
        if([keyPath isEqualToString:@"isTerminated"])
        {
            [[NSWorkspace sharedWorkspace] launchAppWithBundleIdentifier:@"com.apple.finder" options:NSWorkspaceLaunchDefault additionalEventParamDescriptor:NULL launchIdentifier:NULL];
            [object removeObserver:self forKeyPath:@"isTerminated"];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

這是一個applescript方式。 如您所見,您不能依賴特定的延遲時間。 因此,我們通過檢查它是否在正在運行的進程列表中來手動等待Finder退出。 當它不再在列表中時,我們知道它已退出,我們可以再次激活它。

您還會注意到,由於重復循環,我在腳本中進行了時間檢查。 萬一出現問題,我們不希望重復循環永遠運行。 因此,如果它運行10秒鍾以上,我們將自動退出重復循環。

tell application "Finder" to quit

set inTime to current date
repeat
    tell application "System Events"
        if "Finder" is not in (get name of processes) then exit repeat
    end tell
    if (current date) - inTime is greater than 10 then exit repeat
    delay 0.2
end repeat

tell application "Finder" to activate

這是該代碼的osascript版本。

/usr/bin/osascript -e 'tell application "Finder" to quit' -e 'set inTime to current date' -e 'repeat' -e 'tell application "System Events"' -e 'if "Finder" is not in (get name of processes) then exit repeat' -e 'end tell' -e 'if (current date) - inTime is greater than 10 then exit repeat' -e 'delay 0.2' -e 'end repeat' -e 'tell application "Finder" to activate'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM