2010-07-07 107 views
2

我使用的是一個鍵盤密集型應用程序。雙手放在鍵盤上。沒有手的鼠標。選擇popUpContextMenu中的第一個項目

用戶可以通過鍵盤彈出一個上下文菜單,選擇一個項目並最終點擊回車。

[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_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]; 

回答

0

我找到了我原來的問題的答案。但它有問題,我認爲_NSGetCarbonMenu()是必要的,以解決它們。

  1. 問題:一個人如何繪製菜單 項目,所以它看起來像一個本機菜單 項目?
  2. 問題:一個人如何讓 自定義視圖表現爲一個普通的 菜單項..現在你必須 按arrow_down兩次獲得 選擇的下一個項目。

如何解決這些問題?

@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]; 
0

爲了記錄在案,如果你的目標10.6及更高版本,不使用類方法popUpContextMenu,使用實例的popUpMenuPositioningItem:atLocation:inView:。 如果您指定positioningItem它將被自動選擇。當然,您需要重新計算相對於選定項目的位置。

相關問題