Detecting Ctrl + Return or Ctrl + Enter presses

风流意气都作罢 提交于 2020-01-04 06:48:33

问题


I find it very hard to find anything official on this matter.

I have a TextView and override the keyDown event and try to detect if the user pressed Ctrl + Enter.

- (void)keyDown:(NSEvent *)theEvent
{
    if([theEvent modifierFlags] & NSControlKeyMask && /* how to check if enter is pressed??? */)
    {
        NSLog(@"keyDown: ctrl+enter");
        if(_delegate)
        {
            if([_delegate respondsToSelector:@selector(didSomething:)])
            {
                [_delegate performSelector:@selector(didSomething:) withObject:nil];
            }
        }
    }else
    {
        [super keyDown:theEvent];
    }
}

I have tried different things but nothing worked.

anyone?

(i'm sorry to ask such a trivial question but i have googled for a while now and haven't found anything)


回答1:


unichar c = [theEvent charactersIgnoringModifiers] characterAtIndex:0];

if(([theEvent modifierFlags] & NSControlKeyMask) && (c == NSCarriageReturnCharacter || c == NSEnterCharacter) {
    // do stuff
}

Alternatively, you can use the delegate's textView:doCommandBySelector::

- (BOOL)textView:(NSTextView *)aTextView doCommandBySelector:(SEL)aSelector {
    // insertLineBreak: is the method sent when a user presses control-return in a text view
    if (aSelector == @selector(insertLineBreak:)) {
            // do stuff
            return YES;
        }
    }

    return NO;
}



回答2:


Instead of overriding -keyDown:, you could override the keyboard action (insert a line break) that’s sent when ctrl-return is typed in a text view:

- (void)insertLineBreak:(id)sender {
    NSLog(@"ctrl-return");

    if(_delegate)
    {
        …
    }
}


来源:https://stackoverflow.com/questions/7361168/detecting-ctrl-return-or-ctrl-enter-presses

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