【问题标题】:How can I change the Dock preferences programmatically?如何以编程方式更改 Dock 首选项?
【发布时间】:2018-03-20 04:58:17
【问题描述】:

我是 Cocoa/macOS 编程的新手。我刚刚发现NSUserDefaults 可用于更改应用程序/系统设置,就像defaults 命令所做的那样。

但我不知道如何更新这些设置。

例如,我使用NSUserDefaults 将扩展坞大小设置为 32,并同步设置。但 Dock 保留了旧设置。

即使我使用defaults write com.apple.dock tilesize 32 更改其大小,在我注销并登录之前它也不会更新。

是否有任何其他技术可以通知扩展坞获取更新?我知道系统偏好设置可以做到这一点。

谢谢!

【问题讨论】:

    标签: objective-c cocoa macos desktop


    【解决方案1】:

    Mac OS X 扩展坞在被杀死并重新启动之前不会重新加载其设置。就像您必须通过终端 (defaults write com.apple.dock tilesize 32; killall Dock) 手动更改其设置一样,您必须在代码中执行此操作。因此,虽然您已经编写了代码的 defaults 部分,但您必须编写 kill 部分:

    NSRunningApplication *dock = [NSRunningApplication runningApplicationWithBundleIdentifier:@"com.apple.dock"];
    [dock terminate];
    

    如果您想在不杀死码头的情况下执行此操作,对不起,但您不走运。虽然可能有一个隐藏的 API 可以强制扩展坞即时重新加载其设置,但在我的所有搜索中,我从未发现任何关于如何做到这一点的提示(大多数应用程序的隐藏分布式通知中心上没有发布通知相互交流)。

    【讨论】:

      【解决方案2】:

      借助 Xcode 调试器的魔力和一些格式化的反汇编,我创建了这个简短的头文件,您可以将其粘贴到您的代码中(GitHub 要点是 here)。函数名称希望是不言自明的。

      // TO USE THESE INTERFACES, you MUST link against ApplicationServices.framework.
      
      #pragma once
      
      #ifdef __cplusplus
      extern "C" {
      #endif
      
          // Boolean preferences
          extern void CoreDockSetLaunchAnimationsEnabled(bool enable);
          extern void CoreDockSetMagnificationEnabled(bool enable);
          extern void CoreDockSetAutoHideEnabled(bool enable);
          extern void CoreDockSetMinimizeInPlace(bool enable);
      
          // Sets other preferences such as whether the indicators below the app icons are shown
          // 'preferenceDict' is a CFDictionary containing a magic key value
          // Will require further inspection of Dock.prefpane to find all the keys
          // (I haven't noted them down)
          extern void CoreDockSetPreferences(CFDictionaryRef preferenceDict);
      
      #ifdef __cplusplus
      } // extern "C"
      #endif
      

      以这种方式更新的首选项会立即反映,因为这些函数实际上在内部向“com.apple.dock”mach 服务发送消息。
      玩得开心!

      请注意:这些是私有系统 API。提交到 Mac App Store 的任何使用这些 API 的应用程序都将被拒绝。另一方面,如果您没有 App Store 的意图,那么使用这些界面并没有什么坏处。它们似乎在 Mac OS X 诞生之初就已经存在,而且它们极不可能在不久的将来消失,如果有的话。

      【讨论】:

        【解决方案3】:

        您可以使用 AppleScript 通过编写系统偏好设置脚本来设置扩展坞的一些属性,您可能想看看是否可以采用这种方法?也许从您的应用中调用一些 AppleScript?

        【讨论】:

          猜你喜欢
          • 2014-11-24
          • 1970-01-01
          • 2012-05-29
          • 1970-01-01
          • 1970-01-01
          • 2023-03-21
          • 1970-01-01
          • 2017-03-24
          • 1970-01-01
          相关资源
          最近更新 更多