启动以运行和隐藏应用程序

时间:2011-01-28 03:06:15

标签: objective-c launchd

所以我有一个应用程序'myApp',我倾向于在登录时加载'myApp'。 我通过launchd获得了这一切:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key>
      <string>com.myAppDomain.myApp</string>
    <key>ProgramArguments</key>
      <array>
        <string>/Applications/myApp.app/Contents/MacOS/myApp</string>
      </array>
    <key>RunAtLoad</key>
      <true/>
  </dict>
</plist>

我还想让用户同时隐藏'myApp'

我尝试创建一个bash脚本,并添加到我的lauchd plist中的ProgramArguments数组中:

#!/bin/sh

osascript=/usr/bin/osascript

$osascript -e 'tell application "System Events" to set visible of process "'myApp'" to false'

exit 0

但这可能无法运行,或者更有可能在我的应用有机会初始化之前运行。

有一种更简单的方法可以做到这一点,我只是忽略了吗? 提前谢谢。

2 个答案:

答案 0 :(得分:1)

你可以通过调用

在你的偏好plist中设置一个bool
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HideOnLaunch"];

当用户选择在启动时隐藏您的应用。

然后,当您的应用通过launchd启动时,您的应用本身可以检查HideOnLaunch中的applicationDidFinishLaunching:设置,并相应地隐藏自己:

if([[NSUserDefaults standardUserDefaults] boolForKey:@"HideOnLaunch"]){
     [[NSApplication sharedApplication] hide:nil];
}

不要让launchd隐藏您的应用!

另一种方法如下:您可以轻松地将参数传递给Cocoa程序。如this NSUserDefaults document中所述,如果您启动这样的Cocoa应用程序:

AnApp.app/Contents/MacOS/AnApp -FuBar YES

然后,您可以通过YES获取值[[NSUserDefaults standardUserDefaults] boolForKey:@"FuBar"]

因此,根据用户的偏好,您可以编写launchd plist设置参数-HideOnLaunch YES-HideOnLaunch NO

因此,在您的应用代理中,大概在applicationDidFinishLaunching:,根据程序参数是否隐藏您的应用  HideOnLaunch已设置。

答案 1 :(得分:0)

谢谢Yuji。

我最终得到了这样一个推出的plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
    <string>com.myAppDomain.MyApp</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/sh</string>
        <string>-c</string>
        <string>/Applications/MyApp.app/Contents/MacOS/MyApp -hideOnLogin YES</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

我在ProgramArguments键中添加了bash脚本作为字符串,就像Apple在以下plist中所做的那样:

~/Library/LaunchAgents/com.apple.FTMonitor.plist

hideOnLogin键只能通过launchd plist访问,并在myApp退出时重置。我有一个复选框绑定到另一个键“hideOnLoad”,当这个更改时,我将启动的plist重写为:

/Applications/MyApp.app/Contents/MacOS/MyApp -hideOnLogin YES

/Applications/MyApp.app/Contents/MacOS/MyApp

视情况而定。

在启动时,我检查两个默认值是否都为真,如果是,我隐藏myApp,如下所示:     [NSApp hide:self];

再次感谢我指出了正确的方向!