How to force an NSWindow to be always active/focused?

佐手、 提交于 2019-12-05 11:01:44

If you add a borderless NSButton instance to your window's view and set your image as the button's image (and as its alternate image, to make it more beautiful), it will work out of the box: Just connect the button's action method to your app delegate (or the object where you want to process the click action). A click on the image (i.e. the button) will then trigger the button's action method, no matter which window is active.

I'm not sure if this is exactly what you want (it's not quite a window wide setting), but, from the documentation:

By default, a mouse-down event in a window that isn’t the key window simply brings the window forward and makes it key; the event isn’t sent to the NSView object over which the mouse click occurs. The NSView can claim an initial mouse-down event, however, by overriding acceptsFirstMouse: to return YES.

The argument of this method is the mouse-down event that occurred in the non-key window, which the view object can examine to determine whether it wants to receive the mouse event and potentially become first responder. You want the default behavior of this method in, for example, a control that affects the selected object in a window.

However, in certain cases it’s appropriate to override this behavior, such as for controls that should receive mouseDown: messages even when the window is inactive. Examples of controls that support this click-through behavior are the title-bar buttons of a window.

Or you could try fiddling with

- (void)sendEvent:(NSEvent *)theEvent

and see if you can handle events in a custom way.

This worked for me, hope that will be helpful, This will keep your window always on Top of all applications

[self.window makeKeyAndOrderFront:nil];
[self.window setLevel:NSStatusWindowLevel];

I think what you really should do is use an NSPanel (a floating palette -- a special kind of NSWindow) that will do exactly what you want in a way that's consistent with the OS rather than trying to fight intended behavior.

Here's the NSPanel documentation:

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/nspanel_Class/Reference/Reference.html

And here's some helpful and pithy information:

http://cocoadev.com/wiki/NSPanel

By default, an NSPanel will disappear when the application is inactive, but you can turn this off.

I apologize for not laying it out more fully ... pressed for time.

Edit:

Note that you can probably get your window to behave as desired simply:

"The NSView can claim an initial mouse-down event, however, by overriding acceptsFirstMouse: to return YES."

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/EventOverview/HandlingMouseEvents/HandlingMouseEvents.html

You'll need to do this with any NSView subclass to skip the "activation click".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!