No input to NSTextField when running macruby

2019-07-18 11:15发布

i have a simple macruby application and i want to get some user-input via a NSTextField, but when i run the application with '''macruby test.rb''' all the input on the focused text-field goes into the bash. is there something that i need to set, to get the input into the text-field?

# test.rb
framework 'AppKit'

application = NSApplication.sharedApplication
frame = [0.0, 0.0, 300, 200]
window = NSWindow.alloc.initWithContentRect(frame,
                                            styleMask: NSTitledWindowMask | NSClosableWindowMask,
                                            backing: NSBackingStoreBuffered,
                                            defer: false)

content_view = NSView.alloc.initWithFrame(frame)
window.contentView = content_view

tf = NSTextField.alloc.initWithFrame([125, 30, 120, 20])
window.contentView.addSubview(tf)

window.display
window.makeKeyAndOrderFront(nil)

application.run

2条回答
Juvenile、少年°
2楼-- · 2019-07-18 11:50

You need to add the following code (anywhere before application.run):

application.activationPolicy = NSApplicationActivationPolicyRegular

I'm quite new to MacRuby myself, but this seems to be necessary because the default activation policy for unbundled applications is "NSApplicationActivationPolicyProhibited".

See Apple's documentation for more detail.

You may also find it useful to activate your application with the following:

application.activateIgnoringOtherApps(true) 

If you use this second line of code it's worth reading through question 5032203. As you know: it is considered impolite to steal focus, so you'd want to remove this if you ever bundled your app for distribution.

查看更多
Melony?
3楼-- · 2019-07-18 11:56

See this thread on the MacRuby mailing list.

To answer the question, here is the code needed to let your app have focus when started from the command line:

NSApplication.sharedApplication.activationPolicy = NSApplicationActivationPolicyRegular
NSApplication.sharedApplication.activateIgnoringOtherApps(true)
查看更多
登录 后发表回答