Cocoa WebView不响应键盘事件

时间:2017-04-10 11:52:10

标签: objective-c macos cocoa webview webkit

我在纯Objective-C中制作超级简单的单页浏览器,除键盘事件外,一切都很好。我只是无法使用键盘在webforms中输入任何数据!鼠标操作就像粘贴在webforms中并点击链接一样,但输入webforms却不行!

代码:

#import <WebKit/WebKit.h>

@interface MyWebView : WebView
{
}
@end

@implementation MyWebView

-(void)windowWillClose:(NSNotification *)notification
{
    [NSApp terminate:self];
}

-(BOOL)becomeFirstResponder
{
    printf("becomeFirstResponder\n"); // this message always appears
    return YES;
}

-(void)keyDown:(NSEvent *)event
{
    printf("keydown\n"); // this message never appears
    // should I use this code to make keyboard work?
    [self interpretKeyEvents:[NSArray arrayWithObject:event]];
}

@end

int main(void) {
    NSRect contentRect;
    NSWindow *window = nil;
    WebView *webView = nil;
    NSString *urlForAuthentication = nil;

    NSApp = [NSApplication sharedApplication];

    contentRect = NSMakeRect(100, 100, 700, 700);
    window = [[NSWindow alloc] initWithContentRect:contentRect styleMask:NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask backing:NSBackingStoreBuffered defer:NO];
    if (!window) {
        printf("!window\n");
        goto end;
    }
    webView = [[MyWebView alloc] initWithFrame:window.contentLayoutRect frameName:nil groupName:nil];
    if (!webView) {
        printf("!webView\n");
        goto end;
    }

    urlForAuthentication = [[NSString alloc] initWithCString:(const char *)"https://yahoo.com" encoding:NSUTF8StringEncoding];
    [[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlForAuthentication]]];
    window.contentView = webView;
    window.delegate = (id)webView;
    [window makeFirstResponder:webView];
    [window makeKeyAndOrderFront:nil];
    [window makeMainWindow];

    if (!window.keyWindow)
        printf("not keyWindow\n"); // this message always appears
    if (!window.mainWindow)
        printf("not mainWindow\n"); // this message always appears
    [NSApp run];

end:
    [urlForAuthentication release];
    [webView release];
    [window release];
    [NSApp release];
    return 0;
}

生成文件:

CC=clang

FRAMEWORKS:=/System/Library/Frameworks/WebKit.framework/WebKit /System/Library/Frameworks/AppKit.framework/AppKit
LIBRARIES:=
WARNINGS=-Wall -Werror

SOURCE=app.m

CFLAGS=-g -v $(WARNINGS) $(SOURCE)
LDFLAGS=$(LIBRARIES) $(FRAMEWORKS) $(LINK_WITH)
OUT=-o app

all:
    $(CC) $(CFLAGS) $(LDFLAGS) $(OUT)

我做错了什么?我已经阅读了文档并在SO上搜索了类似的问题,但我找不到解决方案。我试图捕获keyDown事件,但它不会发生。我试图让我的窗口键和主要,但看似不成功。

1 个答案:

答案 0 :(得分:0)

可能关注的人:将可执行文件'abc'放在'abc.app/Contents/MacOS/'文件夹中,它最终会正常工作!