How to make NSWindow handle the mouseDown event without focus?

Now I have a borderless window that handles the mouse down event to move and resize itself. But how can I handle the mouse down event without focus?

+3
source share
2 answers

In your user view, the method should be implemented -acceptsFirstMouse:and return YES.

+6
source

[NSWindow windowNumberAtPoint:mouseDownCoordinates belowWindowWithWindowNumber:0];

Pass mouseDownCoordinatesin, which you would capture through Quartz Event Services . It will return the number of the window the mouse is over. Take this window and make your transition / resize.

Implementation example (mainly from here ):

#import <ApplicationServices/ApplicationServices.h>

// Required globals/ivars:
// 1) CGEventTap eventTap is an ivar or other global
// 2) NSInteger (or int) myWindowNumber is the window
//    number of your borderless window

void createEventTap(void)
{
 CFRunLoopSourceRef runLoopSource;

 CGEventMask eventMask = NSLeftMouseDownMask; // mouseDown event

 //create the event tap
 eventTap = CGEventTapCreate(kCGSessionEventTap,
            kCGHeadInsertEventTap, // triggers before other event taps do
            kCGEventTapOptionDefault,
            eventMask,
            myCGEventCallback, //the callback we receive when the event fires
            nil); 

 // Create a run loop source.
 runLoopSource = 
   CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);

 // Add to the current run loop.
 CFRunLoopAddSource(CFRunLoopGetCurrent(),
                    runLoopSource,
                    kCFRunLoopCommonModes);

 // Enable the event tap.
 CGEventTapEnable(eventTap, true);
}


//the CGEvent callback that does the heavy lifting
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef theEvent, void *refcon)
{
 // handle the event here
 if([NSWindow windowNumberAtPoint:CGEventGetLocation(theEvent)
     belowWindowWithWindowNumber:0] == myWindowNumber)
 {
   // now we know our window is the one under the cursor
 }

 // If you do the move/resize at this point,
 // then return NULL to prevent anything else
 // from responding to the event,
 // otherwise return theEvent.

 return theEvent;
}
+2
source

Source: https://habr.com/ru/post/1796191/


All Articles