咨询HandlerUtil中getCurrentSelection与getActiveMenuSelection的区别
Great question—this is one of those Eclipse API nuances that’s easy to mix up because they overlap so often, but their underlying context sources make them behave differently in specific scenarios. Let me break this down based on how Eclipse’s context system works and my own experience with these methods:
Underlying Context Keys & Sources
HandlerUtil.getCurrentSelection()pulls from the active workbench window's global selection context (backed by theISources.ACTIVE_CURRENT_SELECTIONkey). This is the "main" selection across the entire workbench—think of it as whatever’s selected in the currently focused view or editor.HandlerUtil.getActiveMenuSelection()retrieves the selection that was active at the moment the menu was triggered (backed byISources.ACTIVE_MENU_SELECTION). This is tightly tied to the menu’s invocation context, which might not align with the global selection in certain cases.
When They Match (and When They Don’t)
- Same Return Value: Most of the time, especially when you click a menu item from the main menu bar while a view/editor has focus, both methods will return the same object. That’s because the global selection matches the context the menu was launched in.
- Different Return Values:
- Context Menu on a Non-Focused Element: If you right-click an element in a view that’s not the currently focused one (say, you have the Project Explorer open but focus is on an editor),
getActiveMenuSelection()will return the element you right-clicked, whilegetCurrentSelection()will stick to the editor’s selection. - Delayed Command Execution: If your command takes time to run (like a long-running operation) and the user changes the global selection mid-execution,
getCurrentSelection()will pick up the new selection, butgetActiveMenuSelection()will retain the exact selection that was present when the user first clicked the menu.
- Context Menu on a Non-Focused Element: If you right-click an element in a view that’s not the currently focused one (say, you have the Project Explorer open but focus is on an editor),
Which One to Use?
- Go with
getActiveMenuSelection()when your command is triggered from a menu (especially context menus) and you need to act on the exact element the user interacted with to open the menu. This guarantees you’re working with the selection the user intended, even if the global selection shifts. - Use
getCurrentSelection()when you need the most up-to-date selection in the workbench, regardless of how the command was invoked (e.g., keyboard shortcuts, toolbar buttons that aren’t tied to a specific menu context).
- Go with
内容的提问来源于stack exchange,提问作者Stefan Winkler
相关产品推荐
相关产品推荐

