代码之家  ›  专栏  ›  技术社区  ›  neoneye

选择popUpContextMenu中的第一项

  •  2
  • neoneye  · 技术社区  · 14 年前

    我在一个键盘密集型应用程序上工作。双手放在键盘上。不要把手放在老鼠身上。

    [NSMenu popUpContextMenu] 显示菜单而不突出显示任何项目。用户必须按下向下箭头一次,以突出显示第一项。

    我的一个朋友注意到,每次使用这个菜单时,你都必须按下箭头\,然后

    我怀疑这需要碳黑客?

    如何以编程方式突出显示第一项?


    我用这个代码弹出一个菜单。

    NSEvent* event = [NSEvent otherEventWithType:NSApplicationDefined
        location:location 
        modifierFlags:0 
        timestamp:0
        windowNumber:[[self window] windowNumber]
        context:[[self window] graphicsContext]
        subtype:100
        data1:0
        data2:0
    ];
    [NSMenu popUpContextMenu:menu withEvent:event forView:self];
    

    更新:我已经尝试在popUpContextMenu之后发送一个arrow\u down事件给我的应用程序,但是当菜单可见时,该事件不会执行(该事件在菜单消失后执行)。

    unichar code = NSDownArrowFunctionKey;
    NSString* chars = [NSString stringWithFormat: @"%C", code];
    NSEvent* event = [NSEvent keyEventWithType:NSKeyDown location:location modifierFlags:0 timestamp:0 windowNumber:[[self window] windowNumber] context:[[self window] graphicsContext] characters:chars charactersIgnoringModifiers:chars isARepeat:NO keyCode:code];
    [NSApp sendEvent:event];
    
    2 回复  |  直到 14 年前
        1
  •  0
  •   neoneye    14 年前

    我已经找到了我原来问题的答案。但是它有问题,我认为 _NSGetCarbonMenu()

    1. 问题:如何绘制菜单 使其看起来像本地菜单 物品?
    2. 自定义视图的行为与普通视图相同 向下按两次箭头键以获得 已选择下一项。

    如何解决这些问题?

    @interface MyMenuItem : NSView {
        BOOL m_active;
    }
    @end
    
    @implementation MyMenuItem
    - (BOOL)acceptsFirstResponder { return YES; }
    - (BOOL)becomeFirstResponder { m_active = YES; return YES; }
    - (BOOL)resignFirstResponder { m_active = NO; return YES; }
    
    - (void)viewDidMoveToWindow { [[self window] makeFirstResponder:self]; }
    
    - (void)drawRect:(NSRect)rect {
        if(m_active) {
            [[NSColor blueColor] set];
        } else {
            [[NSColor blackColor] set];
        }
        NSRectFill(rect);
    }
    @end
    
    
    // this makes sure the first item gets selected when the menu popups
    MyMenuItem* view = [[[MyMenuItem alloc] initWithFrame:NSMakeRect(0, 0, 100, 20)] autorelease];
    [view setAutoresizingMask:NSViewWidthSizable];
    NSMenuItem* item = [menu itemAtIndex:0];
    [item setView:view];
    [NSMenu popUpContextMenu:menu withEvent:event forView:self];
    

    // simulate a key press of the arrow-down key
    CGKeyCode key_code = 125;  // kVK_DownArrow = 125
    CGEventRef event1, event2;
    event1 = CGEventCreateKeyboardEvent(NULL, key_code, YES);
    event2 = CGEventCreateKeyboardEvent(NULL, key_code, NO);
    CGEventPost(kCGSessionEventTap, event1);
    CGEventPost(kCGSessionEventTap, event2);
    CFRelease(event1);
    CFRelease(event2);
    
    [NSMenu popUpContextMenu:menu withEvent:event forView:self];
    
        2
  •  0
  •   ivarni    9 年前

    popUpContextMenu ,使用实例的 popUpMenuPositioningItem:atLocation:inView: 如果您指定 positioningItem 它将被自动选择。当然,您需要重新计算相对于所选项目的位置。