如何使用 MacRuby 读取全局选择?
如何在 MacRuby 中读取全局 UI 选择?例如,预览中选定的文本。
由于没有 Ruby 和 Cocoa 的经验,我决定冒险编写一个小型词典应用程序来帮助自己进行翻译。所有的部分都准备好了,我只需要知道如何阅读热键上选定的文本。
How can I read a global UI selection within MacRuby? For instance, of selected text in Preview.
Having no experience in Ruby and Cocoa, I've decided to take a plunge and to write a small dictionary app to aid myself with translation. All the pieces are ready, I just need to know how to read selected text on hotkey.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能,因为没有。
没有一种全球选择。每个文本视图(或其他包含可选文本的视图)有一个文本选择。窗口可以具有任意数量的这样的视图,应用程序可以打开任意数量的这样的窗口,并且用户可以运行任意数量的这样的应用程序。
另一个问题是并非所有应用程序都是 Cocoa。其中,大多数都可以访问,但不是全部;自定义视图可能会让您感到困惑(例如,想想图形编辑器中的文本工具)。如果用户在非 Cocoa 应用程序中选择文本,您很可能无法阅读它。
如果您想访问焦点应用程序中焦点窗口的焦点视图中选定的文本,最好的方法是让您的应用程序提供 Service,用户可以从几乎任何 Cocoa 应用程序和一些更开明的 Carbon 应用程序中调用它。这是你能做的最好的事情了。
Apple 自己的词典在 AppKit 中得到特殊对待(包括 Cocoa 和 Carbon 应用程序中浮动词典面板的可用性),但其他方面的工作方式相同:它提供了一项显示在每个服务菜单中的服务(如果用户没有打开)关闭)。
You can't, because there isn't one.
There is not one global selection. There is one text selection per text view (or other selectable-text-containing view). A window may have any number of such views, an application may have any number of such windows open, and the user may have any number of such applications running.
A further problem is that not all applications are Cocoa. Of those that are, most are accessible, but not all; custom views may trip you up (think of the Text tool in a graphics editor, for example). If the user selects text in a non-Cocoa application, chances are you won't be able to read it.
If you want to access the selected text in the focused view in the focused window in the focused application, the best way to do that is to make your application provide a Service, which the user can invoke from nearly any Cocoa application and some of the more enlightened Carbon apps. That's the best you can do.
Apple's own Dictionary gets special treatment in AppKit (including the availability of a floating Dictionary panel in Cocoa and Carbon apps), but otherwise works the same way: It provides a service that shows up in every Services menu (if the user hasn't turned it off).