2

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
phoet
  • 18,688
  • 4
  • 46
  • 74

2 Answers2

2

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.

Community
  • 1
  • 1
Antony Perkov
  • 931
  • 6
  • 13
  • Thanks—I was having this problem and it worked great for me. I wonder why this isn't mentioned in the MacRuby tutorials?? Seems pretty essential as it wasn't at all obvious this is what was needed to get things to work correctly. – Jonathan Beebe May 11 '12 at 20:16
2

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)
Matt Aimonetti
  • 1,112
  • 1
  • 10
  • 11