objective-c - Cocoa/Objective-C - 从其他窗口层发送/接收点击?

标签 objective-c macos cocoa

我正在制作一个类似于GeekTool的应用程序。我不太熟悉 GeekTool 的内部工作原理,但它的外观和行为很相似。基本上我有一个覆盖整个屏幕的无边框窗口,效果很好。目前,我的窗口位于 'kCGDesktopIconWindowLevel' 层,但是我无法与桌面上的任何内容进行交互(移动/打开文件等)。当我的窗口位于该级别以下一层 (kCGDesktopIconWindowLevel-1) 时,我可以与桌面交互,但不能与我的窗口交互,并且我需要能够交互。我是否可以接收来自上层的点击或将它们发送到下层?

顺便说一句,如果您对如何实现这一目标但避免这个问题有更好的想法,我将不胜感激。

最佳答案

我建议您在 applicationDidFinishLaunching: 中创建一个像这样的事件点击(从 this answer 提升):

CGEventMask emask;
CFMachPortRef myEventTap;
CFRunLoopSourceRef eventTapRLSrc;

// We only want one kind of event at the moment: Left mouse down
emask = CGEventMaskBit(kCGEventLeftMouseDown);

// Create the Tap
myEventTap = CGEventTapCreate (
    kCGSessionEventTap, // Catch all events for current user session
    kCGTailAppendEventTap, // Append to end of EventTap list
    kCGEventTapOptionListenOnly, // We only listen, we don't modify
    emask,
    &myEventTapCallback,
    NULL // We need no extra data in the callback
);

// Create a RunLoop Source for it
eventTapRLSrc = CFMachPortCreateRunLoopSource(
    kCFAllocatorDefault,
    myEventTap,
    0
);

// Add the source to the current RunLoop
CFRunLoopAddSource(
    CFRunLoopGetCurrent(),
    eventTapRLSrc,
    kCFRunLoopDefaultMode
);

将窗口设置为通常忽略鼠标事件 - [myWindow setIgnoresMouseEvents: YES];

然后你的事件点击将寻找它想要“捕获”的鼠标点击——如下所示:

static CGEventRef myEventTapCallback (
    CGEventTapProxy proxy,
    CGEventType type,
    CGEventRef event,
    void * refcon
) {
    CGPoint mouseLocation;

    // If we would get different kind of events, we can distinguish them
    // by the variable "type", but we know we only get mouse moved events

    mouseLocation = CGEventGetLocation(event);

    // Figure out if the mouse is clicking on something we want to "catch"
    if (/* want this click */)
       [myWindow setIgnoresMouseEvents: NO];

    // Pass on the event, we must not modify it anyway, we are a listener
    return event;
}

鼠标事件完成后,将窗口返回到忽略鼠标事件。

关于objective-c - Cocoa/Objective-C - 从其他窗口层发送/接收点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13635056/

相关文章:

xcode - 如何对二维多维 NSMutablearray 进行排序

objective-c - 使用 Cocoa 自动布局在自定义 View 中填充内容

PHP脚本不会在后台运行

macos - 从 find : why is -not -path not working? 中排除子目录

macos - 在服务器端验证 Mac OS X 的消耗品应用内购买

objective-c - 如何使 Mac 上的对象消失?

cocoa - 绑定(bind) NSMenuItem 的标题会破坏启用/禁用验证

iphone - 减速移动 UIView

ios - 如何从 UITableView 获取所有加载的单元格?

iphone - 检查设备iOS平台是否存在重载方法