Focus() public method

public Focus ( ) : bool
return bool
Beispiel #1
0
        private void FlickerFocusToForceBindingCommit()
        {
            Control currentControl = Keyboard.FocusedElement as Control;

            if (currentControl != null)
            {
                // Force focus away from the current control to update its binding source.
                currentControl.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                currentControl.Focus();
                // moving next is not enough, as the next item could be a menu item (in a different focus
                // scope) so also try the previous command.
                currentControl.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
                currentControl.Focus();
            }
        }
        private static void TrySetText(Control element, string text)
        {
            var peer = FrameworkElementAutomationPeer.FromElement(element);
            var provider = peer == null ? null : peer.GetPattern(PatternInterface.Value) as IValueProvider;

            if (provider != null)
            {
                provider.SetValue(text);
            }
            else if (element is TextBox)
            {
                var textBox = element as TextBox;
                textBox.Text = text;
                textBox.SelectionStart = text.Length;
            }
            else if (element is PasswordBox)
            {
                var passwordBox = element as PasswordBox;
                passwordBox.Password = text;
            }
            else
            {
                throw new AutomationException("Element does not support SendKeys.", ResponseStatus.UnknownError);
            }

            // TODO: new parameter - FocusState
            element.Focus();
        }
 public static void Focus(Control control)
 {
     if (control == null)
     {
         return;
     }
     var window = Window.GetWindow(control);
     if (window == null)
     {
         return;
     }
     //can't invoke Focus when window is inactive
     //since this causes issues with Window.Activated event and Window.IsActive value
     if (window.IsActive)
     {
         _controlToFocus = null;
         control.Focus();
     }
     else
     {
         window.Activated -= Window_Activated;
         window.Activated += Window_Activated;
         _controlToFocus = control;
     }
 }
Beispiel #4
0
        /// <summary>
        /// Forces lost focus on the active control in a Window to force the selected control
        /// to databind.
        /// Typical scenario: Toolbar clicks (which don't cause a focus change) don't see
        /// latest control state of the active control because it doesn't know focus has
        /// changed. This forces the active control to unbind
        /// </summary>
        /// <param name="window">Active window</param>
        /// <param name="control">Control to force focus to briefly to force active control to bind</param>
        public static void FixFocus(Window window, System.Windows.Controls.Control control)
        {
            var ctl = FocusManager.GetFocusedElement(window);

            if (ctl == null)
            {
                return;
            }

            control.Focus();
            window.Dispatcher.Invoke(() => ctl.Focus(), DispatcherPriority.ApplicationIdle);
        }
Beispiel #5
0
        public static void SetTextboxTextValue([NotNull] System.Windows.Controls.TextBox textBox, [NotNull] string value, [CanBeNull] System.Windows.Controls.Control otherControl)
        {
            Assert.ArgumentNotNull(textBox, "textBox");
            Assert.ArgumentNotNull(value, "value");

            textBox.Text = value;
            textBox.Focus();
            if (otherControl != null)
            {
                otherControl.Focus();
            }
        }
Beispiel #6
0
        /// <summary>
        /// Forces lost focus on the active control in a Window to force the selected control
        /// to databind.
        /// Typical scenario: Toolbar clicks (which don't cause a focus change) don't see
        /// latest control state of the active control because it doesn't know focus has
        /// changed. This forces the active control to unbind
        /// </summary>
        /// <param name="window">Active window</param>
        /// <param name="control">Control to force focus to briefly to force active control to bind</param>
        public static void FixFocus(Window window, System.Windows.Controls.Control control)
        {
            var ctl = FocusManager.GetFocusedElement(window);

            if (ctl == null)
            {
                return;
            }

            control.Focus();
            DoEvents();
            ctl.Focus();
        }
Beispiel #7
0
 private bool Check(string data, string name, System.Windows.Controls.Control ctrlFocus = null, string tip = "不能为空")
 {
     if (string.IsNullOrEmpty(data))
     {
         System.Windows.MessageBox.Show($"{name}{tip}!");
         if (ctrlFocus != null)
         {
             ctrlFocus.Focus();
         }
         return(false);
     }
     return(true);
 }
        public OKCancelControlContainer(Control control, string caption)
            : this()
        {
            Name = control.Name;

            if (string.IsNullOrEmpty(Name))
            {
                var type = control.GetType();
                //если контрол собственный, а Name не задан - то подставл¤ем им¤ типа
                Name = type.Namespace.StartsWith("System.")?null:type.Name;
            }

            if (string.IsNullOrEmpty(Name))
                throw new ArgumentException(Properties.Resources.ControlNameCanNotBeEmpty);
            Title = caption;

            double initialViewWidth = control.Width;
            double initialViewHeight = control.Height;

            Width = initialViewWidth + 22;
            Height = initialViewHeight + 77;

            if (control.MinWidth != 0)
                MinWidth = control.MinWidth + 22;

            if (control.MinHeight != 0)
                MinHeight = control.MinHeight + 77;

            //			if (control.MaxWidth != 0)
            //				MaxWidth = control.MaxWidth + 22;
            //
            //			if (control.MaxHeight != 0)
            //				MaxHeight = control.MaxHeight + 77;

            control.Width = Double.NaN;
            control.Height = Double.NaN;

            Control = control;

            //если контрол может сам посылать сообщение о закрытии - то подключаем соответствующий обработчик
            if (control is IClosable)
                ((IClosable)control).CloseFired += ClosableControl_CloseFired;

            control.Focus();
        }
Beispiel #9
0
        public static string PickFile([NotNull] string message, [CanBeNull] System.Windows.Controls.TextBox textBox, [CanBeNull] System.Windows.Controls.Control otherControl, [NotNull] string pattern)
        {
            Assert.ArgumentNotNullOrEmpty(message, "message");
            Assert.ArgumentNotNullOrEmpty(pattern, "pattern");

            OpenFileDialog fileBrowserDialog = new OpenFileDialog
            {
                Title           = message,
                Multiselect     = false,
                CheckFileExists = true,
                Filter          = pattern
            };

            string filePath = textBox != null ? textBox.Text : string.Empty;
            string fileName = Path.GetFileName(filePath);

            if (!string.IsNullOrEmpty(fileName) && SIM.FileSystem.FileSystem.Local.File.Exists(filePath))
            {
                fileBrowserDialog.FileName         = fileName;
                fileBrowserDialog.InitialDirectory = Path.GetDirectoryName(filePath);
            }

            if (fileBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                if (textBox != null)
                {
                    textBox.Text = fileBrowserDialog.FileName;
                    textBox.Focus();
                    if (otherControl != null)
                    {
                        otherControl.Focus();
                    }
                }

                return(fileBrowserDialog.FileName);
            }

            return(null);
        }
 /// <summary>
 /// Method used to show warnings of required text fields.
 /// </summary>
 /// <param name="control">The text field</param>
 /// <param name="message">Warning message</param>
 private void ShowRequiredWarning(Control control, string message)
 {
     MessageBox.Show(message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
     control.Focus(); //Focus on the required control.
 }
 /// <summary>
 /// 恢复导航到控件的初始值
 /// </summary>
 /// <param name="ToControl"></param>
 private void ResetToPt(Control ToControl, double left, double opc)
 {
     ToControl.Opacity = opc;
     ToControl.Margin = new Thickness(left, 0, 0, 0);
     ToControl.RenderTransform = new CompositeTransform();
     ToControl.RenderTransformOrigin = new Point(0.5, 0.5);
     ToControl.Visibility = System.Windows.Visibility.Visible;
     ToControl.Focus();
 }
       /* private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (!IsInvalid())
            {
                if (txtTarget.Text.Trim() == "" || Convert.ToDouble(txtTarget.Text) <= 0)
                {
                    MessageBox.Show("For target enter a number greater than 0.");
                    return;
                }
                _vm.Save();
            }
            dgTargets.ItemsSource = _vm.OutletTargets;
        }*/

    /*    bool IsInvalid()
        {
            var validationContext = new ValidationContext(LayoutRoot.DataContext, null, null);
            List<ValidationResult> validationResults = new List<ValidationResult>();
            var isInvalid = false;

            var selectedRoute = cmbRoutes.SelectedText as MasterEntity;
            if (selectedRoute.Id == Guid.Empty)
            {
                ValidationResult vr = new ValidationResult(true, _messageResolver.GetText("sl.target.validation.selectroute")/*"Select route"#1#);
                HighlightControl(cmbRoutes, vr);
                isInvalid = true;
            }

            var selectedOutlet = cmbOutlets.SelectedValue as MasterEntity;
            if (selectedOutlet == null || selectedOutlet.Id == Guid.Empty)
            {
                ValidationResult vr = new ValidationResult(true, _messageResolver.GetText("sl.target.validation.selectoutelt")/*"Select outlet"#1#);
                HighlightControl(cmbOutlets, vr);
                isInvalid = true;
            }

            var selectedPeriod = cmbPeriod.SelectedValue as MasterEntity;
            if (selectedPeriod.Id == Guid.Empty)
            {
                ValidationResult vr = new ValidationResult(true, _messageResolver.GetText("sl.target.validation.selecttargetperiod")/*"Select target period"#1#);
                HighlightControl(cmbPeriod, vr);
                isInvalid = true;
            }

            //if (Convert.ToDouble(txtTarget.Text) <= 0)
            //{
            //    ValidationResult vr = new ValidationResult("Enter target value greater than 0");
            //    HighlightControl(cmbPeriod, vr);
            //    isInvalid = true;
            //}

            if (!Validator.TryValidateObject(LayoutRoot.DataContext, validationContext, validationResults as ICollection<System.ComponentModel.DataAnnotations.ValidationResult>))
            {
                //foreach (var error in validationResults)
                //    HighlightControl(dictValidationControls[error.MemberNames.First()], error);
                isInvalid = true;
            }

            return isInvalid;
        }*/

        #region Validation
        void HighlightControl(Control control, ValidationResult result)
        {
            //ToolTip tooltip = GetTooltip(control);

            //tooltip.DataContext = result.ErrorMessage;

            //tooltip.Template = this.Resources["ValidationToolTipTemplate"] as ControlTemplate;

            if (!control.Focus())
                VisualStateManager.GoToState(control, "InvalidUnfocused", true);
            else
                VisualStateManager.GoToState(control, "InvalidFocused", true);
        }
        public override void ResultMessageBox(MessageBoxResult _MessageBoxResult, Control _errCtl)
        {
            if (_MessageBoxResult == MessageBoxResult.OK)
            {
                #region 更新処理

                switch (this.utlFunctionKey.gFunctionKeyEnable)
                {
                    case Utl_FunctionKey.geFunctionKeyEnable.New:
                    case Utl_FunctionKey.geFunctionKeyEnable.Init:
                        UpdateData(Common.geUpdateType.Insert);
                        break;
                    case Utl_FunctionKey.geFunctionKeyEnable.Upd:
                        UpdateData(Common.geUpdateType.Update);
                        break;
                    default:
                        break;
                }

                #endregion
            }
            else
            {
                if (_errCtl != null)
                {
                    switch (_errCtl.Name)
                    {
                        case "dg":
                            _errCtl.Focus();
                            this.dg.SelectedIndex = _selectIndex;
                            dg.CurrentColumn = dg.Columns[_selectColumn];
                            break;
                        default:
                            ExBackgroundWorker.DoWork_Focus(_errCtl, 10);
                            break;
                    }
                }
            }
        }
Beispiel #14
0
		static public void CheckDefaultMethods (Control c)
		{
			Assert.IsFalse (c.ApplyTemplate (), "ApplyTemplate");
			Assert.IsFalse (c.Focus (), "Focus");
		}
 public void setActiveControl(Control c)
 {
     activecontrol = c;
     c.Focus();
 }
 private void move(List<Control> c, int move)
 {
     cursorindex = c.IndexOf(activecontrol) + move;
     checkIndex(c);
     activecontrol = c[cursorindex];
     activecontrol.Focus();
 }
Beispiel #17
0
        static void RunCommand_Reset(object sender, ExecutedRoutedEventArgs e)
        {
            var cnc = FanucCnc.CncScreenDisplay.CreateInstance();

            Messenger.Default.Send <string>("RESET", "CsdKeyMsg");

            if (_CurrentControl == null)
            {
                return;
            }


            _CurrentControl.Focus();
        }
Beispiel #18
0
 private static void MarkErrorField(Control control, Label label = null)
 {
     control.Background = new SolidColorBrush(Colors.MistyRose);
     if (label != null)
         label.Foreground = new SolidColorBrush(Colors.Red);
     control.Focus();
     Keyboard.Focus(control);
 }
 private void PromptUserForInput(string message, Control control)
 {
     if (_messageBoxIsShown)
         return;
     _messageBoxIsShown = true;
     MessageBox.Show(message);
     _messageBoxIsShown = false;
     control.Focus();
 }
Beispiel #20
0
 bool ValidateControl(Control control, string messageString)
 {
     if (control is TextEdit)
     {
         if (string.IsNullOrEmpty((control as TextEdit).Text))
         {
             MessageBox.Show("请填写" + messageString);
             control.Focus();
             return false;
         }
         return true;
     }
     if (control is ComboBoxEdit)
     {
         if ((control as ComboBoxEdit).SelectedIndex == -1)
         {
             MessageBox.Show("请填写" + messageString);
             control.Focus();
             return false;
         }
         return true;
     }
     if (control is ComboBox)
     {
         if ((control as ComboBox).SelectedIndex == -1)
         {
             MessageBox.Show("请填写" + messageString);
             control.Focus();
             return false;
         }
         return true;
     }
     //MessageBox.Show("请填写" + messageString);
     return true;
 }
        private void SetFocusAfterDelay(Control ctl)
        {
            // This is horrible but is needed to get around some WPF weirdness with setting the focus

            Thread.Sleep(100);

            Dispatcher.BeginInvoke((ThreadStart)delegate()
            {
                ctl.Focus();
                FocusManager.SetFocusedElement(ctl, ctl);
                Keyboard.Focus(ctl);

            });
        }
        public override void ResultMessageBox(MessageBoxResult _MessageBoxResult, Control _errCtl)
        {
            if (_MessageBoxResult == MessageBoxResult.OK)
            {
                #region 更新処理

                UpdateData();

                #endregion
            }
            else
            {
                switch (_errCtl.Name)
                {
                    case "dg":
                        _errCtl.Focus();
                        this.dg.SelectedIndex = _selectIndex;
                        dg.CurrentColumn = dg.Columns[_selectColumn];
                        ExBackgroundWorker.DoWork_Focus(_errCtl, 10);
                        break;
                    default:
                        ExBackgroundWorker.DoWork_Focus(_errCtl, 10);
                        break;
                }
            }
        }
Beispiel #23
0
        static void RunCommand_Q(object sender, ExecutedRoutedEventArgs e)
        {
            if (_CurrentControl == null)
            {
                return;
            }

            Keyboard.Type(Key.Q);
            //Keyboard.Press(Key.LeftShift);
            _CurrentControl.Focus();
        }
Beispiel #24
0
 public static void SetFocus(Control control)
 {
     if (control.Dispatcher.CheckAccess())
     {
         control.Focus();
     }
     else
     {
         control.Dispatcher.BeginInvoke(new SetFocusDelegate(SetFocus), control);
     }
 }
Beispiel #25
0
 private void changeVisibiliteText(Control from, Control to)
 {
     to.Visibility = Visibility.Visible;
     to.Focus();
     from.Visibility = Visibility.Collapsed;
 }
        /// <summary>
        /// Called when [channel add animation complete].
        /// </summary>
        /// <param name="channelAddControl">The channel add control.</param>
        private void OnChannelAddAnimationComplete(ChannelAddControl channelAddControl)
        {
            if (transitionContainer.Items.Count == 0)
            {
                // Set Canvas Top
                if (channelAddControl.ChannelConfiguration.DisplayStyle == DisplayStyle.Other)
                {
                    Canvas.SetTop(ChannelSetupStackPanel, 0);
                }
                else
                {
                    Canvas.SetTop(ChannelSetupStackPanel, 110);
                }

                // Tranisition Settings
                transitionContainer.Opacity = 0;

                // Setup Control
                ChannelSetupControl setupControl = new ChannelSetupControl(channelAddControl.ChannelConfiguration.Clone());
                setupControl.IsInEditModus = false;
                setupControl.OnValidationFinished += OnValidationFinishedHandler;
                setupControl.OnCancel += OnCancelHandler;
                setupControl.RenderTransform = new TranslateTransform(0, 0);
                setupControl.OnFormLayoutUpdated +=
                    delegate
                    {
                        // Set Canvas Top
                        if (setupControl.ChannelConfiguration.DisplayStyle == DisplayStyle.Other ||
                            setupControl.IsManuallyCustomized)
                        {
                            Canvas.SetTop(ChannelSetupStackPanel, 0);
                        }
                        else
                        {
                            Canvas.SetTop(ChannelSetupStackPanel, 110);
                        }
                    };

                transitionContainer.Items.Add(setupControl);

                // Empty Control
                Control emptyControl = new Control();
                emptyControl.HorizontalAlignment = HorizontalAlignment.Stretch;
                emptyControl.VerticalAlignment = VerticalAlignment.Bottom;
                emptyControl.RenderTransform = new TranslateTransform(0, 0);

                transitionContainer.Items.Add(emptyControl);

                // NOTE: This is a workaround to get the focus
                // correctly on the SetupControl. This way the command binding
                // on the CheckCredentials button is triggerd correctly.
                emptyControl.Focus();
                setupControl.Focus();

                // Animate Opacity Tween
                PennerDoubleAnimation.Equations equation = PennerDoubleAnimation.Equations.QuintEaseOut;
                int durationMS = 750;
                Animator.AnimatePenner(transitionContainer, OpacityProperty, equation, transitionContainer.Opacity, 1, durationMS, delegate { });
            }

            OnPropertyChanged("HasConfiguredChannels");
        }