【问题标题】:Receive global TouchEvents with NSEvent使用 NSEvent 接收全局 TouchEvents
【发布时间】:2013-06-21 12:34:01
【问题描述】:

我只是尝试在窗口中全局接收触摸事件,而不仅仅是在视图中。 在我的代码中,您可以在下面看到,我将在魔术触控板上获得触摸的绝对位置。只要光标在视图内(红色的 NSRect),它就可以正常工作,但是我怎样才能在这个视图之外接收触摸。 我在许多社区和苹果开发中心搜索了解决方案,但一无所获。 我认为问题是这样的:NSSet *touches = [ev touchesMatchingPhase:NSTouchPhaseTouching inView:nil]; NSEvent 中不是有一个方法可以得到每一次触摸吗?

希望有人可以帮助我。

这是我的实现:

@implementation MyView

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
        [self setAcceptsTouchEvents:YES];
        myColor  = [NSColor colorWithDeviceRed:1.0 green:0 blue:0 alpha:0.5];
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    // Drawing code here.
    NSRect bounds = [self bounds];

    [myColor set];
    [NSBezierPath fillRect:bounds];

}

- (void)touchesBeganWithEvent:(NSEvent *)ev {
    NSSet *touches = [ev touchesMatchingPhase:NSTouchPhaseTouching inView:nil];

    for (NSTouch *touch in touches) {

        NSPoint fraction = touch.normalizedPosition;
        NSSize whole = touch.deviceSize;
        NSPoint wholeInches = {whole.width / 72.0, whole.height / 72.0};
        NSPoint pos = wholeInches;
        pos.x *= fraction.x;
        pos.y *= fraction.y;
        NSLog(@"%s: Finger is touching %g inches right and %g inches up "
              @"from lower left corner of trackpad.", __func__, pos.x, pos.y);

    }
}

【问题讨论】:

    标签: objective-c macos cocoa


    【解决方案1】:

    调用touchesMatchingPhase:inView:nil 作为最后一个参数(你正在做的方式)将得到所有的接触。问题是touchesBeganWithEvent: 根本不会为不在触摸区域中的控件触发。

    您可以使视图成为第一响应者,它将首先将所有事件发送给它。见becomeFirstResponderResponder object

    【讨论】:

      猜你喜欢
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多