如何使NSWindow处理mouseDown事件而不关注焦点?

时间:2011-03-04 02:21:28

标签: objective-c cocoa nswindow

现在我有一个无边框窗口,可以处理鼠标按下事件以移动和调整自身大小。但是如何在没有焦点的情况下处理鼠标按下事件?

2 个答案:

答案 0 :(得分:6)

您的自定义视图必须实施-acceptsFirstMouse:方法并返回YES

答案 1 :(得分:2)

[NSWindow windowNumberAtPoint:mouseDownCoordinates belowWindowWithWindowNumber:0];

传递mouseDownCoordinates,您将通过Quartz Event Services捕获。它将返回鼠标悬停在其上的窗口编号。抓住那个窗口然后移动/调整大小。

示例实现(主要取自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;
}