private void UpdateFocusManager() { if (mgrFocus == null) { //please, never do that! mgrFocus = new FocusManagerExt(); mgrFocus.UpdateServiceReferences(this); BindingFlags bf = BindingFlags.Default; bf |= BindingFlags.NonPublic; bf |= BindingFlags.Instance; FieldInfo fi = typeof(Diagram).GetField("m_mgrFocus", bf); fi.SetValue(this, mgrFocus); } }
/// <summary> /// If the TapToNext flag is enabled, this function will try to take the focus to the next focusable element. /// </summary> /// <param name="sender">The RadialController being used.</param> /// <param name="args">The arguments of the changed event.</param> private static void Controller_ButtonClicked(RadialController sender, RadialControllerButtonClickedEventArgs args) { FocusManager.TryMoveFocus(FocusNavigationDirection.Next); }
private UIElement FindFocusCandidate(int clearedIndex, ref UIElement focusedChild) { // Walk through all the children and find elements with index before and after the cleared index. // Note that during a delete the next element would now have the same index. int previousIndex = int.MinValue; int nextIndex = int.MaxValue; UIElement nextElement = null; UIElement previousElement = null; var children = m_owner.Children; for (int i = 0; i < children.Count; ++i) { var child = children[i]; var virtInfo = ItemsRepeater.TryGetVirtualizationInfo(child); if (virtInfo != null && virtInfo.IsHeldByLayout) { int currentIndex = virtInfo.Index; if (currentIndex < clearedIndex) { if (currentIndex > previousIndex) { previousIndex = currentIndex; previousElement = child; } } else if (currentIndex >= clearedIndex) { // Note that we use >= above because if we deleted the focused element, // the next element would have the same index now. if (currentIndex < nextIndex) { nextIndex = currentIndex; nextElement = child; } } } } // Find the next element if one exists, if not use the previous element. // If the container itself is not focusable, find a descendent that is. UIElement focusCandidate = null; if (nextElement != null) { focusedChild = nextElement as UIElement; if (nextElement.Focus()) { focusCandidate = nextElement; } else if (nextElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.First))) { focusCandidate = FocusManager.GetFocusedElement(nextElement) as UIElement; } } if (focusCandidate == null && previousElement != null) { focusedChild = previousElement as UIElement; if (previousElement.Focus()) { focusCandidate = previousElement; } else if (previousElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Last))) { focusCandidate = FocusManager.GetFocusedElement(previousElement) as UIElement; } } return(focusCandidate); }
protected override void OnKeyDown(KeyEventArgs e) { if (!Interaction.AllowKeyDown(e)) { return; } base.OnKeyDown(e); if (e.Handled) { return; } // Some keys (e.g. Left/Right) need to be translated in RightToLeft mode Key invariantKey = InteractionHelper.GetLogicalKey(FlowDirection, e.Key); switch (invariantKey) { case Key.Left: { #if SILVERLIGHT RatingItem ratingItem = FocusManager.GetFocusedElement() as RatingItem; #else RatingItem ratingItem = FocusManager.GetFocusedElement(Application.Current.MainWindow) as RatingItem; #endif if (ratingItem != null) { ratingItem = GetRatingItemAtOffsetFrom(ratingItem, -1); } else { ratingItem = GetRatingItems().FirstOrDefault(); } if (ratingItem != null) { if (ratingItem.Focus()) { e.Handled = true; } } } break; case Key.Right: { #if SILVERLIGHT RatingItem ratingItem = FocusManager.GetFocusedElement() as RatingItem; #else RatingItem ratingItem = FocusManager.GetFocusedElement(Application.Current.MainWindow) as RatingItem; #endif if (ratingItem != null) { ratingItem = GetRatingItemAtOffsetFrom(ratingItem, 1); } else { ratingItem = GetRatingItems().FirstOrDefault(); } if (ratingItem != null) { if (ratingItem.Focus()) { e.Handled = true; } } } break; case Key.Add: { if (!this.IsReadOnly) { RatingItem ratingItem = GetSelectedRatingItem(); if (ratingItem != null) { ratingItem = GetRatingItemAtOffsetFrom(ratingItem, 1); } else { ratingItem = GetRatingItems().FirstOrDefault(); } if (ratingItem != null) { ratingItem.SelectValue(); e.Handled = true; } } } break; case Key.Subtract: { if (!this.IsReadOnly) { RatingItem ratingItem = GetSelectedRatingItem(); if (ratingItem != null) { ratingItem = GetRatingItemAtOffsetFrom(ratingItem, -1); } if (ratingItem != null) { ratingItem.SelectValue(); e.Handled = true; } } } break; } }
/// <summary> /// Default constructor /// </summary> public RadioButton() { ContextMenuService.Coerce(this); FocusManager.SetIsFocusScope(this, true); }
public ServerEditDialog(int m = ServerEditDialog.Modes.Add, IList <IDiscoveredObject> ItemsCollection = null, IList <IDiscoveredObject> ItemsSelection = null) { InitializeComponent(); Mode = new Modes(m); Title = Modes.DialogTypes[Mode]; tbkServerEdit.Text = "Add servers to collect data from with the " + Core.ProductFullName + ", using credentials to read the data."; tbServiceName = new TextBox { }; tbServiceName.TextChanged += tbServiceName_TextChanged; tbServiceName.Style = (Style)FindResource("WizardTextBoxStyle"); Label lblServiceName = new Label { Content = "DNS name or IP address:", Target = tbServiceName }; cbServiceType = new ComboBox { }; cbServiceType.ItemsSource = COptions.DiscoverServers.OrderBy(o => o.ToString()).ToList(); cbServiceType.GotFocus += CbServiceType_GotFocus; Label lblServiceType = new Label { Content = "Server type:", Target = cbServiceType }; tbUsername = new TextBox { }; tbUsername.TextChanged += tbUsername_TextChanged; tbUsername.Style = (Style)FindResource("WizardTextBoxStyle"); Label lblUsername = new Label { Content = "Username:"******"Password:"******"Edit Servers"; tbServiceName.IsEnabled = false; cbServiceType.IsEnabled = false; FocusManager.SetFocusedElement(this, tbUsername); Keyboard.Focus(tbUsername); } } else { cbServiceType.Text = COptions.DiscoverServers[0].ToString(); FocusManager.SetFocusedElement(this, tbServiceName); Keyboard.Focus(tbUsername); } foreach (Control control in ServerEditControls) { control.Height = 25; if (control.GetType().ToString() == "System.Windows.Controls.Label") { control.Margin = new Thickness(-2, 10, 0, 0); } if (control.GetType().ToString() == "System.Windows.Controls.TextBox" || control.GetType().ToString() == "System.Windows.Controls.PasswordBox") { control.VerticalContentAlignment = System.Windows.VerticalAlignment.Center; } DockPanel.SetDock(control, Dock.Top); pnlMain.Children.Add(control); } }
private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { FocusManager.TryMoveFocus(FocusNavigationDirection.Next); }
void Awake() { Instance = this; }
public RegisterUser() { InitializeComponent(); FocusManager.SetFocusedElement(this, this.txtUsuario); }
public Page5() { InitializeComponent(); FocusManager.SetFocusedElement(this, Genius); }
static void lbi_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e) { ListBoxItem lbi = (ListBoxItem)sender; lbi.IsSelected = true; var listBox = ListBox.ItemsControlFromItemContainer(lbi); FrameworkElement focusedElement = (FrameworkElement)FocusManager.GetFocusedElement(FocusManager.GetFocusScope(listBox)); if (focusedElement != null && focusedElement.IsDescendantOf(listBox)) { lbi.Focus(); } }
private void OnAssociatedObjectKeyDown(object sender, [NotNull] KeyEventArgs e) { if (selector.SelectedIndex == -1 || selector.Items.Count == 0) { return; } var window = Window.GetWindow(selector); if (window == null) { return; } // Find the currently focused element (logical focus) var focusedElement = FocusManager.GetFocusedElement(window) as DependencyObject; if (focusedElement == null) { return; } // Because of virtualization, we have to find the container that correspond to the selected item (by its index) var element = selector.ItemContainerGenerator.ContainerFromIndex(selector.SelectedIndex); // focusedElement can be either the current selector or one of its item container if (!ReferenceEquals(focusedElement, selector) && !ReferenceEquals(focusedElement, element)) { // In this case, it means another control is focused, either a control out of scope, or an editing text box in the scope of the item container return; } bool moved; switch (e.Key) { case Key.Right: moved = AssociatedObject.Orientation == Orientation.Vertical ? MoveToNextItem() : MoveToNextLineItem(1); break; case Key.Left: moved = AssociatedObject.Orientation == Orientation.Vertical ? MoveToPreviousItem() : MoveToPreviousLineItem(1); break; case Key.Up: moved = AssociatedObject.Orientation == Orientation.Vertical ? MoveToPreviousLineItem(1) : MoveToPreviousItem(); break; case Key.Down: moved = AssociatedObject.Orientation == Orientation.Vertical ? MoveToNextLineItem(1) : MoveToNextItem(); break; case Key.PageUp: if (AssociatedObject.Orientation == Orientation.Vertical) { var itemHeight = AssociatedObject.ItemSlotSize.Height + AssociatedObject.MinimumItemSpacing * 2.0f; moved = MoveToPreviousLineItem((int)(AssociatedObject.ViewportHeight / itemHeight)); } else { var itemWidth = AssociatedObject.ItemSlotSize.Width + AssociatedObject.MinimumItemSpacing * 2.0f; moved = MoveToPreviousLineItem((int)(AssociatedObject.ViewportWidth / itemWidth)); } break; case Key.PageDown: if (AssociatedObject.Orientation == Orientation.Vertical) { var itemHeight = AssociatedObject.ItemSlotSize.Height + AssociatedObject.MinimumItemSpacing * 2.0f; moved = MoveToNextLineItem((int)(AssociatedObject.ViewportHeight / itemHeight)); } else { var itemWidth = AssociatedObject.ItemSlotSize.Width + AssociatedObject.MinimumItemSpacing * 2.0f; moved = MoveToNextLineItem((int)(AssociatedObject.ViewportWidth / itemWidth)); } break; case Key.Home: moved = selector.Items.MoveCurrentToFirst(); break; case Key.End: moved = selector.Items.MoveCurrentToLast(); break; default: return; } e.Handled = true; if (moved) { if (selector.SelectedIndex > -1) { AssociatedObject.ScrollToIndexedItem(selector.SelectedIndex); if (selector.ItemContainerGenerator != null && selector.SelectedItem != null) { var lbi = selector.ItemContainerGenerator.ContainerFromItem(selector.SelectedItem) as UIElement; lbi?.Focus(); } } } }
protected override void OnDetaching() { FocusManager.RemoveGotFocusHandler(AssociatedObject, OnGotFocus); base.OnDetaching(); }
protected override void OnAttached() { base.OnAttached(); FocusManager.AddGotFocusHandler(AssociatedObject, OnGotFocus); }
private ConsoleApplication() { eventManager = new EventManager(); focusManager = new FocusManager(eventManager); if (!usingJsil) { exitWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); invokeWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset); } }
public void CanReuseElementsDuringUniqueIdReset() { var data = new WinRTCollection(Enumerable.Range(0, 2).Select(i => string.Format("Item #{0}", i))); List <UIElement> mapping = null; ItemsRepeater repeater = null; MockElementFactory elementFactory = null; ContentControl focusedElement = null; RunOnUIThread.Execute(() => { mapping = new List <UIElement> { new ContentControl(), new ContentControl() }; repeater = CreateRepeater( MockItemsSource.CreateDataSource(data, supportsUniqueIds: true), MockElementFactory.CreateElementFactory(mapping)); elementFactory = (MockElementFactory)repeater.ItemTemplate; Content = repeater; repeater.UpdateLayout(); focusedElement = (ContentControl)repeater.TryGetElement(1); focusedElement.Focus(FocusState.Keyboard); }); IdleSynchronizer.Wait(); RunOnUIThread.Execute(() => { elementFactory.ValidateGetElementCalls( new MockElementFactory.GetElementCallInfo(0, repeater), new MockElementFactory.GetElementCallInfo(1, repeater)); elementFactory.ValidateRecycleElementCalls(); data.ResetWith(new[] { data[0], "New item" }); Verify.AreEqual(0, repeater.GetElementIndex(mapping[0])); Verify.AreEqual(1, repeater.GetElementIndex(mapping[1])); Verify.IsNull(repeater.TryGetElement(0)); Verify.IsNull(repeater.TryGetElement(1)); elementFactory.ValidateGetElementCalls(/* GetElement should not be called */); elementFactory.ValidateRecycleElementCalls(/* RecycleElement should not be called */); mapping[1] = new ContentControl(); // For "New Item" repeater.UpdateLayout(); Verify.AreEqual(0, repeater.GetElementIndex(mapping[0])); Verify.AreEqual(1, repeater.GetElementIndex(mapping[1])); Verify.AreEqual(mapping[0], repeater.TryGetElement(0)); Verify.AreEqual(mapping[1], repeater.TryGetElement(1)); elementFactory.ValidateGetElementCalls( new MockElementFactory.GetElementCallInfo(1, repeater)); elementFactory.ValidateRecycleElementCalls( new MockElementFactory.RecycleElementCallInfo(focusedElement, repeater)); // If the focused element survived the reset, we will keep focus on it. If not, we // try to find one based on the index. In this case, the focused element (index 1) // got recycled, and we still have index 1 after the stable reset, so the new index 1 // will get focused. Note that recycling the elements to view generator in the case of // stable reset happens during the arrange, so by that time we will have pulled elements // from the stable reset pool and maybe created some new elements as well. int index = repeater.GetElementIndex(focusedElement); Log.Comment("focused index " + index); Verify.AreEqual(mapping[1], FocusManager.GetFocusedElement()); }); }
private static void IsOpenPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { var dialogHost = (DialogHost)dependencyObject; if (dialogHost._popupContentControl != null) { ValidationAssist.SetSuppress(dialogHost._popupContentControl, !dialogHost.IsOpen); } VisualStateManager.GoToState(dialogHost, dialogHost.SelectState(), !TransitionAssist.GetDisableTransitions(dialogHost)); if (dialogHost.IsOpen) { WatchWindowActivation(dialogHost); dialogHost._currentSnackbarMessageQueueUnPauseAction = dialogHost.SnackbarMessageQueue?.Pause(); } else { dialogHost._asyncShowWaitHandle.Set(); dialogHost._attachedDialogClosingEventHandler = null; if (dialogHost._currentSnackbarMessageQueueUnPauseAction != null) { dialogHost._currentSnackbarMessageQueueUnPauseAction(); dialogHost._currentSnackbarMessageQueueUnPauseAction = null; } dialogHost._session.IsEnded = true; dialogHost._session = null; dialogHost._closeCleanUp(); // Don't attempt to Invoke if _restoreFocusDialogClose hasn't been assigned yet. Can occur // if the MainWindow has started up minimized. Even when Show() has been called, this doesn't // seem to have been set. dialogHost.Dispatcher.InvokeAsync(() => dialogHost._restoreFocusDialogClose?.Focus(), DispatcherPriority.Input); return; } dialogHost._asyncShowWaitHandle.Reset(); dialogHost._session = new DialogSession(dialogHost); var window = Window.GetWindow(dialogHost); dialogHost._restoreFocusDialogClose = window != null?FocusManager.GetFocusedElement(window) : null; //multiple ways of calling back that the dialog has opened: // * routed event // * the attached property (which should be applied to the button which opened the dialog // * straight forward dependency property // * handler provided to the async show method var dialogOpenedEventArgs = new DialogOpenedEventArgs(dialogHost._session, DialogOpenedEvent); dialogHost.OnDialogOpened(dialogOpenedEventArgs); dialogHost._attachedDialogOpenedEventHandler?.Invoke(dialogHost, dialogOpenedEventArgs); dialogHost.DialogOpenedCallback?.Invoke(dialogHost, dialogOpenedEventArgs); dialogHost._asyncShowOpenedEventHandler?.Invoke(dialogHost, dialogOpenedEventArgs); dialogHost.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { CommandManager.InvalidateRequerySuggested(); var child = dialogHost.FocusPopup(); //https://github.com/ButchersBoy/MaterialDesignInXamlToolkit/issues/187 //totally not happy about this, but on immediate validation we can get some weird looking stuff...give WPF a kick to refresh... Tap.Delay(300).ContinueWith(t => child.Dispatcher.BeginInvoke(new Action(() => child.InvalidateVisual()))); })); }
/// <summary> /// F1 リボン マスタ検索 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public override void OnF1Key(object sender, KeyEventArgs e) { try { object elmnt = FocusManager.GetFocusedElement(this); var spgrid = ViewBaseCommon.FindVisualParent <GcSpreadGrid>(elmnt as Control); if (spgrid != null) { int cIdx = spgrid.ActiveColumnIndex; int rIdx = spgrid.ActiveRowIndex; #region グリッドファンクションイベント if (spgrid.ActiveColumnIndex == (int)GridColumnsMapping.自社品番) { // 対象セルがロックされている場合は処理しない if (spgrid.Cells[rIdx, cIdx].Locked == true) { return; } // 自社品番または得意先品番の場合 SCHM09_MYHIN myhin = new SCHM09_MYHIN(); myhin.txtCode.Text = spgrid.Cells[rIdx, cIdx].Value == null ? string.Empty : spgrid.Cells[rIdx, cIdx].Value.ToString(); myhin.TwinTextBox = new UcLabelTwinTextBox(); myhin.TwinTextBox.LinkItem = 1; if (myhin.ShowDialog(this) == true) { //入力途中のセルを未編集状態に戻す spgrid.CancelCellEdit(); spgrid.Cells[rIdx, (int)GridColumnsMapping.品番コード].Value = myhin.SelectedRowData["品番コード"].ToString(); spgrid.Cells[rIdx, (int)GridColumnsMapping.自社品番].Value = myhin.SelectedRowData["自社品番"].ToString(); spgrid.Cells[rIdx, (int)GridColumnsMapping.自社品名].Value = myhin.SelectedRowData["自社品名"].ToString(); spgrid.Cells[rIdx, (int)GridColumnsMapping.数量].Value = 1m; spgrid.Cells[rIdx, (int)GridColumnsMapping.消費税区分].Value = myhin.SelectedRowData["消費税区分"]; spgrid.Cells[rIdx, (int)GridColumnsMapping.商品分類].Value = myhin.SelectedRowData["商品分類"]; //20190624CB-S spgrid.Cells[rIdx, (int)GridColumnsMapping.色コード].Value = myhin.SelectedRowData["自社色"]; spgrid.Cells[rIdx, (int)GridColumnsMapping.色名称].Value = myhin.SelectedRowData["自社色名"]; //20190624CB-E // 設定自社品番の編集を不可とする spgrid.Cells[rIdx, cIdx].Locked = true; } } else if (spgrid.ActiveColumnIndex == (int)GridColumnsMapping.摘要) { SCHM11_TEK tek = new SCHM11_TEK(); tek.TwinTextBox = new UcLabelTwinTextBox(); if (tek.ShowDialog(this) == true) { spgrid.Cells[rIdx, cIdx].Value = tek.TwinTextBox.Text2; } } SearchDetail.Rows[rIdx].EndEdit(); #endregion } else { ViewBaseCommon.CallMasterSearch(this, this.MasterMaintenanceWindowList); } } catch (Exception ex) { appLog.Error("検索画面起動エラー", ex); this.ErrorMessage = "システムエラーです。サポートへご連絡ください。"; } }
private void WindowOnDeactivated(object sender, EventArgs eventArgs) { _restoreFocusWindowReactivation = _popup != null?FocusManager.GetFocusedElement((Window)sender) : null; }
public UcEscNum(List <int> existingSlaves) { _existingSlaves = existingSlaves; InitializeComponent(); FocusManager.SetFocusedElement(this, ResponseTextBox); }
public ModifyTipoEmpresaView() { InitializeComponent(); FocusManager.SetFocusedElement(this, this.txtNomreStatus); }
//Pete Huber's answer in https://stackoverflow.com/questions/1345391/set-focus-on-textbox-in-wpf //Sets focus on the name textbox private void OnLoad(Object sender, RoutedEventArgs e) { //No idea why this class needs this here and not so in other classes FocusManager.SetFocusedElement(this, this.GivenTitleTextBox); }
/// <summary> /// Override to create the required scene /// </summary> protected override void OnCreate() { // Up call to the Base class first base.OnCreate(); // Get the main window instance, change background color & respond to key events Window mainWindow = Window.Instance; mainWindow.BackgroundColor = Color.Red; mainWindow.KeyEvent += OnKeyEvent; var layout = new LinearLayout() { LinearOrientation = LinearLayout.Orientation.Horizontal, Padding = new Extents(30, 0, 30, 0), CellPadding = new Size2D(30, 0), }; View menuView = new View() { Layout = layout, WidthSpecification = LayoutParamPolicies.MatchParent, HeightSpecification = LayoutParamPolicies.MatchParent, BackgroundColor = new Color(0.61f, 0.59f, 0.64f, 1.0f), }; mainWindow.Add(menuView); for (int i = 0; i < _textButton.Length; i++) { PropertyMap shadow = new PropertyMap(); shadow.Add("offset", new PropertyValue(new Vector2(2.0f, 2.0f))); shadow.Add("color", new PropertyValue(Color.Black)); shadow.Add("blurRadius", new PropertyValue(5.0f)); // Create a simple TextLabel _textButton[i]._button = new TextLabel(_textButton[i]._text) { Name = "" + _textButton[i]._id, WidthSpecification = 285, HeightSpecification = 130, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Focusable = true, Background = CreateGradientVisual(_textButton[i]._stopColor1, _textButton[i]._stopColor2).OutputVisualMap, TextColor = new Color(0.61f, 0.59f, 0.64f, 1.0f), PointSize = 16, Shadow = shadow, }; // Add the text to the window menuView.Add(_textButton[i]._button); _textButton[i]._button.TouchEvent += OnButtonTouched; } _focusManager = FocusManager.Instance; _focusManager.PreFocusChange += OnPreFocusChange; _focusManager.FocusChanged += OnFocusChanged; _focusManager.FocusedViewActivated += OnFocusedViewEnterKey; _focusManager.SetAsFocusGroup(menuView, true); _focusManager.FocusIndicator = new View(); }
// handle keyboard navigation (tabs and gamepad) private void HamburgerMenu_KeyDown(object sender, KeyRoutedEventArgs e) { var currentItem = FocusManager.GetFocusedElement() as FrameworkElement; var lastItem = LoadedNavButtons.FirstOrDefault(x => x.HamburgerButtonInfo == (SecondaryButtons.LastOrDefault(a => a != Selected) ?? PrimaryButtons.LastOrDefault(a => a != Selected))); var focus = new Func <FocusNavigationDirection, bool>(d => { if (d == FocusNavigationDirection.Next) { return(FocusManager.TryMoveFocus(d)); } else if (d == FocusNavigationDirection.Previous) { return(FocusManager.TryMoveFocus(d)); } else { var control = FocusManager.FindNextFocusableElement(d) as Control; return(control?.Focus(FocusState.Programmatic) ?? false); } }); var escape = new Func <bool>(() => { if (DisplayMode == SplitViewDisplayMode.CompactOverlay || DisplayMode == SplitViewDisplayMode.Overlay) { IsOpen = false; } if (Equals(ShellSplitView.PanePlacement, SplitViewPanePlacement.Left)) { ShellSplitView.Content.RenderTransform = new TranslateTransform { X = 48 + ShellSplitView.OpenPaneLength }; focus(FocusNavigationDirection.Right); ShellSplitView.Content.RenderTransform = null; } else { ShellSplitView.Content.RenderTransform = new TranslateTransform { X = -48 - ShellSplitView.OpenPaneLength }; focus(FocusNavigationDirection.Left); ShellSplitView.Content.RenderTransform = null; } return(true); }); var previous = new Func <bool>(() => { if (Equals(currentItem, HamburgerButton)) { return(true); } else if (focus(FocusNavigationDirection.Previous) || focus(FocusNavigationDirection.Up)) { return(true); } else { return(escape()); } }); var next = new Func <bool>(() => { if (Equals(currentItem, HamburgerButton)) { return(focus(FocusNavigationDirection.Down)); } else if (focus(FocusNavigationDirection.Next) || focus(FocusNavigationDirection.Down)) { return(true); } else { return(escape()); } }); if (IsFullScreen) { return; } switch (e.Key) { case VirtualKey.Up: case VirtualKey.GamepadDPadUp: if (!(e.Handled = previous())) { Debugger.Break(); } break; case VirtualKey.Down: case VirtualKey.GamepadDPadDown: if (!(e.Handled = next())) { Debugger.Break(); } break; case VirtualKey.Right: case VirtualKey.GamepadDPadRight: if (SecondaryButtonContainer.Items.Contains(currentItem?.DataContext) && SecondaryButtonOrientation == Orientation.Horizontal) { if (Equals(lastItem.FrameworkElement, currentItem)) { if (!(e.Handled = escape())) { Debugger.Break(); } } else { if (!(e.Handled = next())) { Debugger.Break(); } } } else { if (!(e.Handled = escape())) { Debugger.Break(); } } break; case VirtualKey.Left: case VirtualKey.GamepadDPadLeft: if (SecondaryButtonContainer.Items.Contains(currentItem?.DataContext) && SecondaryButtonOrientation == Orientation.Horizontal) { if (Equals(lastItem.FrameworkElement, currentItem)) { if (!(e.Handled = escape())) { Debugger.Break(); } } else { if (!(e.Handled = previous())) { Debugger.Break(); } } } else { if (!(e.Handled = escape())) { Debugger.Break(); } } break; case VirtualKey.Space: case VirtualKey.Enter: case VirtualKey.GamepadA: if (currentItem != null) { var info = new InfoElement(currentItem); var hamburgerButtonInfo = info.HamburgerButtonInfo; if (hamburgerButtonInfo != null) { NavCommand.Execute(hamburgerButtonInfo); } } break; case VirtualKey.Escape: case VirtualKey.GamepadB: if (!(e.Handled = escape())) { Debugger.Break(); } break; } }
private void OpenFileDialogView_OnLoaded(object sender, RoutedEventArgs e) { FocusManager.SetFocusedElement(this, PART_Path); Keyboard.Focus(PART_Path); }
/// <summary> /// Custom keyboarding logic to enable movement via the arrow keys without triggering selection /// until a 'Space' or 'Enter' key is pressed. /// </summary> /// <param name="e"></param> protected override void OnKeyDown(KeyRoutedEventArgs e) { var focusedItem = FocusManager.GetFocusedElement(); switch (e.Key) { case VirtualKey.Up: this.TryMoveFocus(FocusNavigationDirection.Up); e.Handled = true; break; case VirtualKey.Down: this.TryMoveFocus(FocusNavigationDirection.Down); e.Handled = true; break; case VirtualKey.Tab: var shiftKeyState = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Shift); var shiftKeyDown = (shiftKeyState & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down; // If we're on the header item then this will be null and we'll still get the default behavior. if (focusedItem is ListViewItem) { var currentItem = (ListViewItem)focusedItem; bool onlastitem = currentItem != null && this.IndexFromContainer(currentItem) == this.Items.Count - 1; bool onfirstitem = currentItem != null && this.IndexFromContainer(currentItem) == 0; if (!shiftKeyDown) { if (onlastitem) { this.TryMoveFocus(FocusNavigationDirection.Next); } else { this.TryMoveFocus(FocusNavigationDirection.Down); } } else // Shift + Tab { if (onfirstitem) { this.TryMoveFocus(FocusNavigationDirection.Previous); } else { this.TryMoveFocus(FocusNavigationDirection.Up); } } } else if (focusedItem is Control) { if (!shiftKeyDown) { this.TryMoveFocus(FocusNavigationDirection.Down); } else // Shift + Tab { this.TryMoveFocus(FocusNavigationDirection.Up); } } e.Handled = true; break; case VirtualKey.Space: case VirtualKey.Enter: // Fire our event using the item with current keyboard focus this.InvokeItem(focusedItem); e.Handled = true; break; default: base.OnKeyDown(e); break; } }
private async void ButtonCardItem_PreviewKeyDown(object sender, KeyRoutedEventArgs e) { FlipViewBanner.UpdateLayout(); VerticalRepeater.UpdateLayout(); FindNextElementOptions findNextElementOptions = new FindNextElementOptions { SearchRoot = ScrollViewerHome, XYFocusNavigationStrategyOverride = XYFocusNavigationStrategyOverride.NavigationDirectionDistance }; //Before move focus //Get current item data context var currentItem = (sender as Button).DataContext as ProductItem; var currentFocusElement = FocusManager.GetFocusedElement() as Button; switch (e.OriginalKey) { case VirtualKey.Up: case VirtualKey.GamepadDPadUp: case VirtualKey.GamepadLeftThumbstickUp: case VirtualKey.Down: case VirtualKey.GamepadDPadDown: case VirtualKey.GamepadLeftThumbstickDown: { //if (!canTap) //{ // e.Handled = true; // return; //} //canTap = false; } break; case VirtualKey.Left: case VirtualKey.GamepadDPadLeft: case VirtualKey.GamepadLeftThumbstickLeft: { } break; case VirtualKey.Right: case VirtualKey.GamepadDPadRight: case VirtualKey.GamepadLeftThumbstickRight: { } break; case VirtualKey.GamepadA: case VirtualKey.Enter: case VirtualKey.Space: { } break; default: break; } try { switch (e.OriginalKey) { case VirtualKey.Up: case VirtualKey.GamepadDPadUp: case VirtualKey.GamepadLeftThumbstickUp: { //BringIntoViewOptions options = new BringIntoViewOptions //{ // VerticalOffset = 50.0, // AnimationDesired = true //}; ////var tt = currentFocusElement.TransformToVisual(appWindow.Content); ////Point currentFocusLeftTopPoint = tt.TransformPoint(new Point(appWindow.Bounds.Left, appWindow.Bounds.Top)); ////Rect rect = new Rect(124, currentFocusLeftTopPoint.Y - 500, 1920, 500); ////var nextFocus = FocusManager.FindNextFocusableElement(FocusNavigationDirection.Next, rect); //var candidate = FocusManager.FindNextElement(FocusNavigationDirection.Up, findNextElementOptions); //if (candidate != null && candidate is Button) //{ // (candidate as Control).StartBringIntoView(); // (candidate as Control).Focus(FocusState.Programmatic); // e.Handled = true; //} //else if(candidate != null) //{ // var current = FlipViewBanner.SelectedItem; // var currentContainer = FlipViewBanner.ContainerFromItem(current) as FlipViewItem; // var result = await FocusManager.TryFocusAsync(currentContainer, FocusState.Programmatic); // currentContainer.StartBringIntoView(); // e.Handled = true; //} if (!canTap) { return; } canTap = false; riverIndex--; if (riverIndex < 0) { var current = FlipViewBanner.SelectedItem; var currentContainer = FlipViewBanner.ContainerFromItem(current) as FlipViewItem; var result = await FocusManager.TryFocusAsync(currentContainer, FocusState.Programmatic); currentContainer.StartBringIntoView(); canTap = true; e.Handled = true; return; } try { Debug.WriteLine("River index: " + riverIndex); var grid = VerticalRepeater.TryGetElement(riverIndex) as Grid; if (grid != null) { grid.StartBringIntoView(); var horizontalRepeater = TreeHelper.FindVisualChild <ItemsRepeater>(grid); if (horizontalRepeater != null) { horizontalRepeater.UpdateLayout(); var lastFocusedItem = horizontalRepeater.GetOrCreateElement(listIndexes[riverIndex]); var button = TreeHelper.FindVisualChild <Button>(lastFocusedItem); if (button != null) { button.Focus(FocusState.Programmatic); button.StartBringIntoView(); canTap = true; e.Handled = true; } } } } catch { Debug.WriteLine("Do not scroll too fast!!!"); } } break; case VirtualKey.Down: case VirtualKey.GamepadDPadDown: case VirtualKey.GamepadLeftThumbstickDown: { ////Last river //BringIntoViewOptions options = new BringIntoViewOptions //{ // VerticalOffset = -50.0, // AnimationDesired = true //}; //var candidate = FocusManager.FindNextElement(FocusNavigationDirection.Down, findNextElementOptions); //if (candidate != null && candidate is Control) //{ // (candidate as Control).StartBringIntoView(); // (candidate as Control).Focus(FocusState.Programmatic); // e.Handled = true; //} if (!canTap) { return; } canTap = false; riverIndex++; if (riverIndex > listIndexes.Count - 1) { riverIndex--; e.Handled = true; return; } try { Debug.WriteLine("River index: " + riverIndex); var grid = VerticalRepeater.TryGetElement(riverIndex) as Grid; if (grid != null) { grid.StartBringIntoView(); var horizontalRepeater = TreeHelper.FindVisualChild <ItemsRepeater>(grid); if (horizontalRepeater != null) { horizontalRepeater.UpdateLayout(); var lastFocusedItem = horizontalRepeater.GetOrCreateElement(listIndexes[riverIndex]); var button = TreeHelper.FindVisualChild <Button>(lastFocusedItem); //Scroll to last river if (riverIndex == listIndexes.Count - 1) { ScrollViewerHome.ChangeView(0.0f, ScrollViewerHome.ScrollableHeight, 1.0f); } if (button != null) { button.Focus(FocusState.Programmatic); button.StartBringIntoView(); canTap = true; e.Handled = true; } } } } catch { Debug.WriteLine("Do not scroll too fast!!!"); } } break; case VirtualKey.Left: case VirtualKey.GamepadDPadLeft: case VirtualKey.GamepadLeftThumbstickLeft: { var parent = TreeHelper.FindParentByName <ItemsRepeater>(sender as Button, "HorizontalRepeater"); FindNextElementOptions findNextElementOptions1 = new FindNextElementOptions { SearchRoot = parent, XYFocusNavigationStrategyOverride = XYFocusNavigationStrategyOverride.Projection }; var candidate = FocusManager.FindNextElement(FocusNavigationDirection.Left, findNextElementOptions1); if (candidate != null && candidate is Control) { (candidate as Control).StartBringIntoView(); (candidate as Control).Focus(FocusState.Programmatic); e.Handled = true; } else { ShellPage.shellPage.navigationView.IsPaneOpen = true; e.Handled = true; } } break; case VirtualKey.Right: case VirtualKey.GamepadDPadRight: case VirtualKey.GamepadLeftThumbstickRight: { } break; case VirtualKey.GamepadA: case VirtualKey.Enter: case VirtualKey.Space: { } break; default: break; } } catch { } finally { //Debug.WriteLine(DateTime.Now); //await Task.Delay(1000); //Debug.WriteLine("sss " + DateTime.Now); //canTap = true; } }
private void Dispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args) { if (Items.Count == 0) { return; } _lastFocusElement = FocusManager.GetFocusedElement() as Control; if (args.VirtualKey == VirtualKey.Menu) { if (!IsOpened) { if (_isLostFocus) { ((MenuItem)Items[0]).Focus(FocusState.Programmatic); if (!(_lastFocusElement is MenuItem)) { _lastFocusElementBeforeMenu = _lastFocusElement; } if (AllowTooltip) { ShowMenuItemsToolTips(); } else { UnderlineMenuItems(); } if (args.KeyStatus.IsKeyReleased) { _isLostFocus = false; } } else if (!_isLostFocus && args.KeyStatus.IsKeyReleased) { if (AllowTooltip) { HideMenuItemsTooltips(); } else { RemoveUnderlineMenuItems(); } _lastFocusElementBeforeMenu?.Focus(FocusState.Keyboard); } } } else if ((args.KeyStatus.IsMenuKeyDown || !_isLostFocus) && args.KeyStatus.IsKeyReleased) { var gestureKey = MapInputToGestureKey(args.VirtualKey, !_isLostFocus); if (gestureKey == null) { return; } if (MenuItemInputGestureCache.ContainsKey(gestureKey)) { var cachedMenuItem = MenuItemInputGestureCache[gestureKey]; if (cachedMenuItem is MenuItem) { var menuItem = (MenuItem)cachedMenuItem; menuItem.ShowMenu(); menuItem.Focus(FocusState.Keyboard); } } } }
/// <summary> /// Default constructor /// </summary> public RibbonGroupsContainer() : base() { Focusable = false; FocusManager.SetIsFocusScope(this, false); }
protected override void OnLoaded(object sender, RoutedEventArgs e) { base.OnLoaded(sender, e); FocusManager.HideFromToolBar(Handle); FocusManager.MakeUnfocusable(Handle); }
private bool ShouldCancelForwardKeyPress() { var currentTextBox = FocusManager.GetFocusedElement(this) as TextBox; return(currentTextBox != null && currentTextBox.CaretIndex == 3); }
/// <summary> /// Initializes a new instance of the <see cref="UIScreen"/> class. /// </summary> /// <param name="name">The name of the screen.</param> /// <param name="renderer"> /// The renderer that defines the styles and visual appearance for controls in this screen. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> or <paramref name="renderer"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is an empty string. /// </exception> public UIScreen(string name, IUIRenderer renderer) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException("String is empty.", "name"); if (renderer == null) throw new ArgumentNullException("renderer"); Name = name; Renderer = renderer; Style = "UIScreen"; Children = new NotifyingCollection<UIControl>(false, false); Children.CollectionChanged += OnChildrenChanged; _focusManager = new FocusManager(this); ToolTipManager = new ToolTipManager(this); #if !SILVERLIGHT // Call OnVisibleChanged when IsVisible changes. var isVisible = Properties.Get<bool>(IsVisiblePropertyId); isVisible.Changed += (s, e) => OnVisibleChanged(EventArgs.Empty); #endif InputEnabled = true; }
protected virtual bool RequestFocus(FocusState state) { return(FocusManager.SetFocusedElement(this, FocusNavigationDirection.None, state)); }