Re: Swift 3 macOS read keyboard
Re: Swift 3 macOS read keyboard
- Subject: Re: Swift 3 macOS read keyboard
- From: Graham Cox <email@hidden>
- Date: Tue, 11 Oct 2016 09:07:13 +1100
I don’t think this is the right way to do this.
NSWindow, NSWindowController and NSView, NSViewController all inherit from NSResponder, which provide standard methods for dealing with keyUp and keyDown events.
The normal approach to receive these events is to subclass one of these (least likely NSWindow, most likely NSView, but also either of the controller types is a good place, almost always subclassed). If you are trying to avoid subclassing for some reason, then you’re swimming upstream. Why?
The addMonitor… stuff is a last resort for when you just don’t have an NSResponder available, or want to have some sort of sidechain. They’re not the go-to places to receive keyboard input.
A Window doesn’t require text fields to get focus and receive keyboard events. To come back to your original question:
>> What would be the most
>> straightforward way of kicking off keyUp and keyDown from within my main
>> NSViewController so I can read keys?
I’m not sure what you mean by “kicking off”, which sounds like you want to post those events. If you want to receive them, just override -keyUp: and -keyDown: in your controller subclass.
—Graham
> On 11 Oct 2016, at 1:45 AM, Eric E. Dolecki <email@hidden> wrote:
>
> I just discovered
>
> override func keyDown(with event: NSEvent) { }
> override func keyUp(with event: NSEvent) {}
>
> NSEvent.addLocalMonitorForEvents(matching: .keyUp) { (aEvent) -> NSEvent? in
> self.keyUp(with: aEvent)
> return aEvent
> }
> NSEvent.addLocalMonitorForEvents(matching: .keyDown) { (aEvent) ->
> NSEvent? in
> self.keyDown(with: aEvent)
> return aEvent
> }
>
> So I have it working now without subclassing NSView, etc. It took me a
> while to find that bit about NSEvent.addLocalMonitorForEvents...
>
> Eric
>
> On Mon, Oct 10, 2016 at 8:53 AM Eric E. Dolecki <email@hidden> wrote:
>
>> I am delving into macOS development and I'd like to do something simple.
>> Give the Application Window "focus" to receive keyboard events. Meaning no
>> text fields.
>>
>> How exactly do I do this? I've been googling and have seen all kinds of
>> things but none of them have worked out. What would be the most
>> straightforward way of kicking off keyUp and keyDown from within my main
>> NSViewController so I can read keys?
>>
>> Thanks,
>> Eric
>>
> _______________________________________________
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden