0

所以我有一个应用程序'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

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

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

4

2 回答 2

2

您可以通过调用在您的偏好 plist 中设置一个布尔值

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HideOnLaunch"];

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

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

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

不要让launchd隐藏您的应用程序!

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

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

然后你可以YES通过[[NSUserDefaults standardUserDefaults] boolForKey:@"FuBar"].

因此,根据用户的偏好,您可以编写一个launchdplist 设置参数-HideOnLaunch YES-HideOnLaunch NO.

因此,在您的应用程序委托中,大概在 中applicationDidFinishLaunching:,根据是否
HideOnLaunch设置了程序参数来隐藏您的应用程序。

于 2011-01-28T03:41:50.407 回答
0

谢谢宇治。

我最终得到了一个像这样的已启动 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>

我将 bash 脚本作为字符串添加到 ProgramArguments 键中,就像 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];

再次感谢您为我指明正确的方向!

于 2011-01-28T07:46:55.127 回答