Page 1 of 1

Focus, the right way?

Posted: 27 Dec 2015, 00:40
by Roms6
Hello guys,

I've been in trouble recently when looking for using keyboard events with NoesisGUI. Basically, I have a main menu with 3 buttons. This is from my MainMenuView UserControl :
public void OnPostInit()
    {
        Grid = (Grid) Parent;
        _settingsView = (SettingsView) Grid.FindName("settingsView");

        _stackPanel = (StackPanel) FindName("menu");
        _start = (Button)_stackPanel.FindName("start");
        _settings = (Button)_stackPanel.FindName("settings");
        _quit = (Button)_stackPanel.FindName("quit");

        _start.Click += StartOnClick;
        _settings.Click += SettingsOnClick;
        _quit.Click += QuitOnClick;
        _quit.KeyDown += QuitOnKeyDown;

        _quit.Focus();
    }
It seems I'm misunderstanding how focus is handled, because _quit.Focus() doesn't focus this button. QuitOnKeyDown is only fired if I click this button then I press a key.

Re: Focus, the right way?

Posted: 28 Dec 2015, 11:22
by sfernandez
Hi,

When OnPostInit is called the control is not yet attached to the UI tree so it cannot be focused. You should do that logic on the Loaded event, when control is attached to the tree and ready to be shown:
public class MainMenuView: UserControl
{
  public MainMenuView()
  {
    Loaded += MainMenuView_Loaded;
  }
  ...
  void MainMenuView_Loaded(object sender, RoutedEventArgs e)
  {
    _quit.Focus();
  }
} 
Anyway, I found a bug in our code that removes any focused element when application is started. If that is your case, please modify the NoesisGUIPanel.cs script as follows (line 460) while we fix this problem:
bool _appStart = true;
void OnApplicationFocus(bool focused)
{
  if (_uiRenderer != null)
  {
    if (!NoesisGUISystem.SoftwareKeyboardManager.IsOpen)
    {
      if (focused)
      {
        if (!_appStart)
        {
          _appStart = false;
          _uiRenderer.Activate();
        }
      }
      else
      {
        _uiRenderer.Deactivate();
      }
    }
  }
}

Re: Focus, the right way?

Posted: 28 Dec 2015, 17:22
by Roms6
Thanks for the explanation. It worked perfectly after applying the fix you provided :)