How do I prevent menu and toolbar clicks stealing

2019-06-26 03:51发布

问题:

I want to achieve the same effect as in Visual Studio 2010+, where if you float an editor on top of the main form, clicking on a main form menu or toolbar button doesn't cause the main form to steal focus; instead the floating window retains focus.

Without this it becomes impossible to invoke any main menu command that operates on a focused control when the focused control is in a floating window - because the control you wanted to operate on loses focus just as the command is invoked.

(Ironically, if you look closely at this image you'll see that the selection in the editor is muted, indicating that the editor control doesn't have focus. Visual Studio seems to be doing something slightly devious to achieve the illusion that the floating window is still focused.)

回答1:

The solution is very easy if you are using TActionMainMenuBar and TActionToolBar.

First the menu bar: TActionMainMenuBar has a property AutoFocus, which is True by default. Set this to False and then clicking on the menu won't automatically give focus to the form containing the menu. Instead, the form that previously had focus will retain it.

Now the tool bar: TActionToolBar doesn't have an AutoFocus property. Instead you need to handle its OnMouseActivate event and return maNoActivate.

Note that returning maNoActivate from an OnMouseActivate handler doesn't work for all controls. Some controls such as TButton will give themselves the focus when clicked regardless of the return result from the OnMouseActivate handler. But in the case of TActionToolBar we do get the effect we are after.

It took me a while to find this though, and even searching Google for a page containing both 'AutoFocus' and 'OnMouseActivate' elicits no useful results (other than, presumably, this page once it gets indexed). So I hope this answer will help someone else.