Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what situations will WPF give keyboard focus back to the main window?

Tags:

c#

focus

wpf

In a WPF application I'm working on, I have a MenuItem with two items in it. When the MenuItem is clicked, it takes keyboard focus and opens its submenu. When the MenuItem is clicked again, the submenu is closed and for some reason, the main window takes keyboard focus. I need the MenuItem to keep focus.

I have been told that in certain other situations, the main window may be given keyboard focus - for instance, if a control has keyboard focus and IsEnabled or IsVisible becomes false. In which situations does this happen? I've been Googling like crazy but haven't found any information about this.

like image 253
Brian Gradin Avatar asked Oct 23 '14 21:10

Brian Gradin


People also ask

How do I make my keyboard focus?

When an HTML element is able to handle keyboard input, it is said to have focus. Exactly one element is able to have focus in a time. In most browsers, users can move focus by pressing the Tab key and the Shift + Tab keys.

What is focus in WPF?

Keyboard focus refers to the element that is currently receiving keyboard input. There can be only one element on the whole desktop that has keyboard focus. In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true .


1 Answers

As far as I can tell, this is the expected behavior. WPF Menus are focus scopes by default, so any control within the menu that receives focus won't change the main logical focus of the window. Also, certain WPF controls will sometimes call Keyboard.Focus(null); (e.g. Button does this when clicked). This call has the effect of returning the keyboard focus to the main logical focus. I suspect this is also happening when a menu is closed.

Try disabling the focus scope on the menu: <Menu FocusManager.IsFocusScope="False"> When the menu item receives the keyboard focus, and it's not in any focus scope, it will gets the main logical focus. This means the Keyboard.Focus(null) call will keep the focus on the menu item. Jowever, this will also prevent commands in the submenu from returning the focus to the non-menu window content, so routed commands won't be able to find their target.

See "For What was FocusScope Designed?" in Using the WPF FocusScope.

like image 146
Daniel Avatar answered Nov 09 '22 23:11

Daniel