/// <summary> /// Selects all the contents /// </summary> public void SelectAll() { if (textBoxTemplated != null) { textBoxTemplated.SelectAll(); } else { textBox.SelectAll(); } }
public void TrimSelectedTextTest() { AvalonTestRunner.RunInSTA(delegate { TextBox textBox = new TextBox(); //try to trim when there are no text TimePicker.ExposeTrimSelectedText(textBox); Assert.AreEqual("", textBox.Text, "Trim failed"); textBox = new TextBox(); textBox.Text = "10"; textBox.SelectAll(); TimePicker.ExposeTrimSelectedText(textBox); Assert.AreEqual("", textBox.Text, "Trim failed when selection was All"); textBox = new TextBox(); textBox.Text = "10"; textBox.SelectionStart = 0; textBox.SelectionLength = 1; TimePicker.ExposeTrimSelectedText(textBox); Assert.AreEqual("0", textBox.Text, "Trim failed when selection was at the first char"); textBox = new TextBox(); textBox.Text = "10"; textBox.SelectionStart = 1; textBox.SelectionLength = 1; TimePicker.ExposeTrimSelectedText(textBox); Assert.AreEqual("1", textBox.Text, "Trim failed when selection was at the second char"); }); }
/// <summary> /// Selecciona el texto del texbox /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SelectAll(object sender, MouseButtonEventArgs e) { TextBox tb = (sender as TextBox); try { if (tb == null) { return; } if (!tb.IsKeyboardFocusWithin) { index = gridProductosInventario.SelectedIndex; gridProductosInventario.UnselectAll(); gridProductosInventario.UpdateLayout(); gridProductosInventario.SelectedIndex = index; tb.Focus(); tb.SelectAll(); } } catch (Exception ex) { Logger.Error(ex); throw new ExcepcionDesconocida(MethodBase.GetCurrentMethod(), ex); } }
private void BindTree(TreeViewItem item, List<Detail> data) { foreach (var detail in data) { var panel = new WrapPanel(); panel.Children.Add(new TextBlock { Text = detail.DisplayName, FontWeight = FontWeights.Bold, VerticalAlignment = VerticalAlignment.Center }); var t = new TextBox { Text = detail.Value, Margin = new Thickness(5, 0, 0, 0), TextWrapping = TextWrapping.Wrap, //Width = this.Width - 300, BorderBrush = new SolidColorBrush(Colors.White), Padding = new Thickness(0) }; t.MouseEnter += (s, ee) => { t.Focus(); t.SelectAll(); }; panel.Children.Add(t); if (!string.IsNullOrEmpty(detail.Description)) panel.Children.Add(new TextBlock { Text = detail.Description, Margin = new Thickness(5, 0, 0, 0), FontStyle = FontStyles.Italic, TextWrapping = TextWrapping.Wrap, Width = 1050 }); var subItem = new TreeViewItem { Header = panel, }; if (detail.SubDetails != null) { BindTree(subItem, detail.SubDetails); } item.Items.Add(subItem); } }
private void TextBox_GotFocus(object sender, RoutedEventArgs e) { System.Windows.Controls.TextBox tb = (sender as System.Windows.Controls.TextBox); if (tb != null) { tb.SelectAll(); } }
private static void OnKeyboardFocusSelectText(object sender, KeyboardFocusChangedEventArgs e) { C.TextBox textBox = e.OriginalSource as C.TextBox; if (textBox != null) { textBox.SelectAll(); } }
/// <summary> /// Restores old value, saved in Tag property, to textbox. /// </summary> /// <param name="sender"></param> private void RestoreOldValue(object sender) { TextBox myText = (TextBox)sender; if (myText.Text != myText.Tag.ToString()) { myText.Text = myText.Tag.ToString(); myText.SelectAll(); } }
public object Ask(Parameter par) { var vlc = main.Children.FindByName(ValueControl); if (vlc != null) main.Children.Remove(vlc); Question.Text = ""; foreach (string s in par.Question.Split(new[] { "\\n" }, StringSplitOptions.None)) { Question.Inlines.Add(new Run { Text = s }); Question.Inlines.Add(new LineBreak()); } if (par.ParamType == ParamType.PBool) { var value = new ComboBox { Width = 100, Height = 20, Name = ValueControl, Margin = new Thickness(5, 0, 0, 0) }; Grid.SetRow(value, 1); main.Children.Add(value); value.Items.Add(Boolean.TrueString); value.Items.Add(Boolean.FalseString); value.SelectedIndex = 0; value.Focus(); } else { var value = new TextBox { Width = 400, Name = ValueControl, Margin = new Thickness(5, 0, 0, 0) }; Grid.SetRow(value, 1); main.Children.Add(value); if (par.ParamType == ParamType.PDouble || par.ParamType == ParamType.PFuzzy) { value.Text = "0"; value.TextChanged += ValueTextChanged; value.Tag = par.ParamType; } else value.Tag = ParamType.PString; value.SelectAll(); value.Focus(); } if (ShowDialog() == true) { UIElement uie = main.Children.FindByName(ValueControl); if (uie is TextBox) { ParamType pt = (ParamType) (uie as TextBox).Tag; if (pt == ParamType.PDouble || pt == ParamType.PFuzzy) return double.Parse((uie as TextBox).Text); return (uie as TextBox).Text; } if (uie is ComboBox) return bool.Parse((uie as ComboBox).Text); } return null; }
/// <summary> /// Handles click /// </summary> /// <param name="args"></param> protected override void OnClick(RoutedEventArgs args) { if (textBox != null) { Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (ThreadStart)(() => { textBox.SelectAll(); textBox.Focus(); })); } args.Handled = true; base.OnClick(args); }
private bool IsOkay(String input, TextBox sender) { if (input.Length > 0) { return true; } else { MessageBox.Show("Check the input."); sender.Focus(); sender.SelectAll(); return false; } }
private bool IsOkay(String input, TextBox sender) { double number = 0; if (input.Length > 0 && Double.TryParse(input, out number)) { return true; } else { MessageBox.Show("Tarkista syöte."); sender.Focus(); sender.SelectAll(); return false; } }
bool checkSetting(bool result, TextBox textBox, string message, TabItem tab = null) { if (!result) { MessageBox.Show(message, resources["Connect"] as string, MessageBoxButton.OK, MessageBoxImage.Warning); if (tab != null) tab.Focus(); new Action(() => { Dispatcher.BeginInvoke(new Action(() => { textBox.SelectAll(); textBox.Focus(); })); }).BeginInvoke(null, null); } return result; }
/// <summary>Simple input dialog box</summary> /// <returns>null if the dialog box was closed with "cancel", /// otherwise the user input<returns> public static string ShowInputDialog(string initialTitle = "", string initialText = "", string initialInput = null) { // create the dialog content TextBox content = new TextBox() { VerticalAlignment = VerticalAlignment.Bottom, TabIndex = 0 }; content.Text = initialInput; Label lbl = new Label() { Content = initialText, VerticalAlignment = VerticalAlignment.Top, Focusable = false }; Grid g = new Grid() { Height = 50, Focusable = false }; g.Children.Add(content); g.Children.Add(lbl); // create the ModernUI dialog component with the buttons var dlg = new ModernDialog { Title = initialTitle, ShowInTaskbar = false, Content = g, MinHeight = 0, MinWidth = 0, MaxHeight = 480, MaxWidth = 640, }; FocusManager.SetFocusedElement(g, content); content.SelectAll(); dlg.Buttons = new Button[] { dlg.OkButton, dlg.CancelButton }; // register the event to retrieve the result of the dialog box string result = null; dlg.OkButton.Click += (object sender, RoutedEventArgs e) => { result = content.Text; }; dlg.ShowDialog(); return result; }
/// <summary> /// Handles key tip pressed /// </summary> public override void OnKeyTipPressed() { if (!IsTemplateValid()) { return; } // Use dispatcher to avoid focus moving to backup'ed element // (focused element before keytips processing) Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (ThreadStart)(() => { textBox.SelectAll(); textBox.Focus(); })); base.OnKeyTipPressed(); }
/// <summary> /// Handles click /// </summary> /// <param name="args"></param> protected override void OnClick(RoutedEventArgs args) { if (!IsTemplateValid()) { return; } // Use dispatcher to avoid focus moving to backup'ed element // (focused element before keytips processing) Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (ThreadStart)(() => { textBox.SelectAll(); textBox.Focus(); })); args.Handled = true; }
private bool checkInputIsDouble(TextBox input) { double number; bool isNumeric = double.TryParse(input.Text, out number); // out pitää kirjoittaa jos funktio voi sijoittaa takaisin muuttujaan if (!isNumeric) { MessageBox.Show("Kentän "+input.Name+" arvon pitää olla numero!"); input.Focus(); input.SelectAll(); return false; } return true; }
public SearchControl(Reflected refled) { Reflected = refled; nameText = new TextBox(); nameText.SetBinding(TextBox.TextProperty, new Binding("ItemName") { Mode = BindingMode.TwoWay, Source = Reflected}); nameText.SelectAll(); nameText.KeyUp += (sende1, e1) => { if (e1.Key != Key.Enter) return; if (search && nameText.Text.Length >= 4) SearchService(nameText.Text, Reflected.Type); else search = true; }; IsContainsMethod = new CheckBox { Content = "Подстрока" , IsChecked=false }; ResultsList = new StackPanel(); Children.Add(nameText, IsContainsMethod, ResultsList); }
public override FrameworkElement CreateControl(FormItemContext context) { TextBox tb = new TextBox(); // apply [MaxLength(x)] attribute var attr2 = context.PropertyInfo.GetCustomAttribute(typeof(MaxLengthAttribute)) as MaxLengthAttribute; var attr3 = context.PropertyInfo.GetCustomAttribute(typeof(StringLengthAttribute)) as StringLengthAttribute; int maxlength = 0; if (attr2 != null) { maxlength = attr2.Length; } else if (attr3 != null) { maxlength = attr3.MaximumLength; } if(maxlength>0) { tb.MaxLength = maxlength; } if (maxlength > 100) //TODO multiline mode { tb.TextWrapping = System.Windows.TextWrapping.Wrap; tb.AcceptsReturn = true; tb.Height = 50; } var binding = new Binding(context.PropertyInfo.Name) { Mode = BindingMode.TwoWay, }; binding.ValidationRules.Add(new AnnotationValidationRule(context.PropertyInfo)); tb.SetBinding(TextBox.TextProperty, binding); CustomValidation.SetValidationProperty(tb, TextBox.TextProperty); tb.GotFocus += (s, e) => { tb.SelectAll(); }; StyleHelper.ApplyStyle(tb, FormControlConstrants.EDIT_TEXTBOX_STYLE); return tb; }
public WindowUsingItemProperty() { InitializeComponent(); tabControl.TabItemAdded += tabControl_TabItemAdded; tabControl.SelectionChanged += tabControl_SelectionChanged; // these 3 events ensure that all the contents of the textbox are selected on a mouseclick (as per IE) // code borrowed from the Windows Presentation Foundation Forum at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2199428&SiteID=1 textBox.GotKeyboardFocus += delegate(object sender, KeyboardFocusChangedEventArgs e) { System.Windows.Controls.TextBox tb = (sender as System.Windows.Controls.TextBox); if (tb != null) { tb.SelectAll(); } }; textBox.MouseDoubleClick += delegate(object sender, MouseButtonEventArgs e) { System.Windows.Controls.TextBox tb = (sender as System.Windows.Controls.TextBox); if (tb != null) { tb.SelectAll(); } }; textBox.PreviewMouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs e) { System.Windows.Controls.TextBox tb = (sender as System.Windows.Controls.TextBox); if (tb != null) { if (!tb.IsKeyboardFocusWithin) { e.Handled = true; tb.Focus(); } } }; }
public void SetSelectionAllOnGotFocus(System.Windows.Controls.TextBox textbox) { MouseButtonEventHandler _OnPreviewMouseDown = (sender, e) => { System.Windows.Controls.TextBox box = e.Source as System.Windows.Controls.TextBox; box.Focus(); e.Handled = true; }; RoutedEventHandler _OnLostFocus = (sender, e) => { System.Windows.Controls.TextBox box = e.Source as System.Windows.Controls.TextBox; box.PreviewMouseDown += _OnPreviewMouseDown; }; RoutedEventHandler _OnGotFocus = (sender, e) => { System.Windows.Controls.TextBox box = e.Source as System.Windows.Controls.TextBox; box.SelectAll(); box.PreviewMouseDown -= _OnPreviewMouseDown; }; textbox.PreviewMouseDown += _OnPreviewMouseDown; textbox.LostFocus += _OnLostFocus; textbox.GotFocus += _OnGotFocus; }
/// <summary> /// This virtual method is called when ApplicationCommands.Copy command is executed. /// </summary> /// <param name="args"></param> protected virtual void OnExecutedCopy(ExecutedRoutedEventArgs args) { if (ClipboardCopyMode == DataGridClipboardCopyMode.None) { throw new NotSupportedException(SR.Get(SRID.ClipboardCopyMode_Disabled)); } args.Handled = true; // Supported default formats: Html, Text, UnicodeText and CSV Collection<string> formats = new Collection<string>(new string[] { DataFormats.Html, DataFormats.Text, DataFormats.UnicodeText, DataFormats.CommaSeparatedValue }); Dictionary<string, StringBuilder> dataGridStringBuilders = new Dictionary<string, StringBuilder>(formats.Count); foreach (string format in formats) { dataGridStringBuilders[format] = new StringBuilder(); } int minRowIndex; int maxRowIndex; int minColumnDisplayIndex; int maxColumnDisplayIndex; // Get the bounding box of the selected cells if (_selectedCells.GetSelectionRange(out minColumnDisplayIndex, out maxColumnDisplayIndex, out minRowIndex, out maxRowIndex)) { // Add column headers if enabled if (ClipboardCopyMode == DataGridClipboardCopyMode.IncludeHeader) { DataGridRowClipboardEventArgs preparingRowClipboardContentEventArgs = new DataGridRowClipboardEventArgs(null, minColumnDisplayIndex, maxColumnDisplayIndex, true /*IsColumnHeadersRow*/); OnCopyingRowClipboardContent(preparingRowClipboardContentEventArgs); foreach (string format in formats) { dataGridStringBuilders[format].Append(preparingRowClipboardContentEventArgs.FormatClipboardCellValues(format)); } } // Add each selected row for (int i = minRowIndex; i <= maxRowIndex; i++) { object row = Items[i]; // Row has a selecion if (_selectedCells.Intersects(i)) { DataGridRowClipboardEventArgs preparingRowClipboardContentEventArgs = new DataGridRowClipboardEventArgs(row, minColumnDisplayIndex, maxColumnDisplayIndex, false /*IsColumnHeadersRow*/, i); OnCopyingRowClipboardContent(preparingRowClipboardContentEventArgs); foreach (string format in formats) { dataGridStringBuilders[format].Append(preparingRowClipboardContentEventArgs.FormatClipboardCellValues(format)); } } } } ClipboardHelper.GetClipboardContentForHtml(dataGridStringBuilders[DataFormats.Html]); try { DataObject dataObject = new DataObject(); foreach (string format in formats) { dataObject.SetData(format, dataGridStringBuilders[format].ToString(), false /*autoConvert*/); } Clipboard.SetDataObject(dataObject); } catch (SecurityException) { // In partial trust we will have a security exception because clipboard operations require elevated permissions // Bug: Once the security team fix Clipboard.SetText - we can remove this catch // Temp: Use TextBox.Copy to have at least Text format in the clipboard TextBox textBox = new TextBox(); textBox.Text = dataGridStringBuilders[DataFormats.Text].ToString(); textBox.SelectAll(); textBox.Copy(); } }
//checks whether textbox content > 255 when 3 characters have been entered. //clears if > 255, switches to next textbox otherwise private void handleTextChange(TextBox currentBox, TextBox rightNeighborBox) { if (currentBox.Text.Length == 3) { try { Convert.ToByte(currentBox.Text); } catch (Exception exception) when (exception is FormatException || exception is OverflowException) { currentBox.Clear(); currentBox.Focus(); SystemSounds.Beep.Play(); MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (currentBox.CaretIndex != 2 && currentBox != fourthBox) { rightNeighborBox.CaretIndex = rightNeighborBox.Text.Length; rightNeighborBox.SelectAll(); rightNeighborBox.Focus(); } } }
private void Reset(bool setTextKey) { // Detect parameters in the code placeholders.Clear(); parsedText = ""; isPartialString = false; if (initialClipboardText != null) { if (SourceCSharpButton.IsChecked == true) { isPartialString = true; if ((initialClipboardText.StartsWith("\"") || initialClipboardText.StartsWith("@\"")) && initialClipboardText.EndsWith("\"")) { isPartialString = false; } bool inStringLiteral = isPartialString; bool isVerbatimString = false; bool inCharLiteral = false; int parensLevel = 0; int bracketsLevel = 0; int bracesLevel = 0; int lastStringEnd = 0; StringBuilder stringContent = new StringBuilder(); for (int pos = 0; pos < initialClipboardText.Length; pos++) { char ch = initialClipboardText[pos]; char nextChar = pos + 1 < initialClipboardText.Length ? initialClipboardText[pos + 1] : '\0'; if (!inStringLiteral && !inCharLiteral && ch == '\'') { // Start char literal inCharLiteral = true; } else if (inCharLiteral && ch == '\\') { // Escape sequence, skip next character pos++; } else if (inCharLiteral && ch == '\'') { // End char literal inCharLiteral = false; } else if (!inStringLiteral && !inCharLiteral && ch == '@' && nextChar == '"') { // Start verbatim string literal inStringLiteral = true; isVerbatimString = true; if (parensLevel == 0 && bracketsLevel == 0 && bracesLevel == 0 && pos > 0) { string code = initialClipboardText.Substring(lastStringEnd, pos - lastStringEnd); var pd = new PlaceholderData(placeholders.Count + 1, code); if (pd.Code != "") { placeholders.Add(pd); parsedText += "{" + pd.Name + "}"; } } // Handled 2 characters pos++; } else if (!inStringLiteral && !inCharLiteral && ch == '"') { // Start string literal inStringLiteral = true; if (parensLevel == 0 && bracketsLevel == 0 && bracesLevel == 0 && pos > 0) { string code = initialClipboardText.Substring(lastStringEnd, pos - lastStringEnd); var pd = new PlaceholderData(placeholders.Count + 1, code); if (pd.Code != "") { placeholders.Add(pd); parsedText += "{" + pd.Name + "}"; } } } else if (inStringLiteral && !isVerbatimString && ch == '\\') { // Escape sequence, skip next character pos++; switch (nextChar) { case '\'': case '"': case '\\': stringContent.Append(nextChar); break; case '0': stringContent.Append('\0'); break; case 'a': stringContent.Append('\a'); break; case 'b': stringContent.Append('\b'); break; case 'f': stringContent.Append('\f'); break; case 'n': stringContent.Append('\n'); break; case 'r': stringContent.Append('\r'); break; case 't': stringContent.Append('\t'); break; case 'U': long value = long.Parse(initialClipboardText.Substring(pos + 1, 8), System.Globalization.NumberStyles.HexNumber); //stringContent.Append(); // TODO: What does that value mean? pos += 8; break; case 'u': int codepoint = int.Parse(initialClipboardText.Substring(pos + 1, 4), System.Globalization.NumberStyles.HexNumber); stringContent.Append((char) codepoint); pos += 4; break; case 'v': stringContent.Append('\v'); break; case 'x': // TODO: variable length hex value! break; } } else if (inStringLiteral && isVerbatimString && ch == '"' && nextChar == '"') { // Escape sequence, skip next character pos++; stringContent.Append(nextChar); } else if (inStringLiteral && ch == '"') { // End string literal inStringLiteral = false; isVerbatimString = false; lastStringEnd = pos + 1; if (parensLevel == 0 && bracketsLevel == 0 && bracesLevel == 0) { parsedText += stringContent.ToString(); } stringContent.Clear(); } else if (inStringLiteral) { // Append character to text stringContent.Append(ch); } else if (!inStringLiteral && !inCharLiteral && ch == '(') { parensLevel++; } else if (!inStringLiteral && !inCharLiteral && ch == ')') { if (parensLevel > 0) parensLevel--; } else if (!inStringLiteral && !inCharLiteral && ch == '[') { bracketsLevel++; } else if (!inStringLiteral && !inCharLiteral && ch == ']') { if (bracketsLevel > 0) bracketsLevel--; } else if (!inStringLiteral && !inCharLiteral && ch == '{') { bracesLevel++; } else if (!inStringLiteral && !inCharLiteral && ch == '}') { if (bracesLevel > 0) bracesLevel--; } } if (!isPartialString && lastStringEnd < initialClipboardText.Length) { // Some non-string content is still left (parameter at the end) string code = initialClipboardText.Substring(lastStringEnd); var pd = new PlaceholderData(placeholders.Count + 1, code); if (pd.Code != "") { placeholders.Add(pd); parsedText += "{" + pd.Name + "}"; } } if (isPartialString && inStringLiteral && stringContent.Length > 0) { // Save the last string part parsedText += stringContent.ToString(); } } if (SourceXamlButton.IsChecked == true) { parsedText = initialClipboardText; // TODO: Any further processing required? } if (SourceAspxButton.IsChecked == true) { // Decode HTML entities parsedText = initialClipboardText .Replace("<", "<") .Replace(">", ">") .Replace(""", "\"") .Replace("&", "&"); } } TranslationText.Text = parsedText; ParametersLabel.Visibility = Visibility.Collapsed; ParametersGrid.Visibility = Visibility.Collapsed; ParametersGrid.Children.Clear(); if (placeholders.Count > 0) { ParametersLabel.Visibility = Visibility.Visible; ParametersGrid.Visibility = Visibility.Visible; int row = 0; foreach (var pd in placeholders) { var localPd = pd; ParametersGrid.RowDefinitions.Add(new RowDefinition()); TextBox nameText = new TextBox(); nameText.Text = pd.Name; nameText.SelectAll(); nameText.Margin = new Thickness(0, row > 0 ? 4 : 0, 0, 0); nameText.LostFocus += (s, e2) => { UpdatePlaceholderName(localPd, nameText.Text); }; ParametersGrid.Children.Add(nameText); Grid.SetRow(nameText, row); Grid.SetColumn(nameText, 0); TextBox codeText = new TextBox(); codeText.Text = pd.Code; codeText.Margin = new Thickness(4, row > 0 ? 4 : 0, 0, 0); codeText.TextChanged += (s, e2) => { localPd.Code = codeText.Text; }; ParametersGrid.Children.Add(codeText); Grid.SetRow(codeText, row); Grid.SetColumn(codeText, 1); CheckBox quotedCheck = new CheckBox(); quotedCheck.Content = "Q"; quotedCheck.IsChecked = pd.IsQuoted; quotedCheck.Margin = new Thickness(4, row > 0 ? 4 : 0, 0, 0); quotedCheck.VerticalAlignment = VerticalAlignment.Center; quotedCheck.Checked += (s, e2) => { localPd.IsQuoted = true; }; quotedCheck.Unchecked += (s, e2) => { localPd.IsQuoted = false; }; ParametersGrid.Children.Add(quotedCheck); Grid.SetRow(quotedCheck, row); Grid.SetColumn(quotedCheck, 2); row++; } } suggestions.Clear(); if (!String.IsNullOrEmpty(TranslationText.Text)) { ScanAllTexts(MainViewModel.Instance.RootTextKey); } bool havePreviousTextKey = !String.IsNullOrEmpty(prevTextKey); bool haveOtherKeys = suggestions.Count > 0; // Order suggestions by relevance (descending), then by text key suggestions.Sort((a, b) => a.ScoreNum != b.ScoreNum ? -a.ScoreNum.CompareTo(b.ScoreNum) : a.TextKey.CompareTo(b.TextKey)); string nearestMatch = suggestions.Count > 0 ? suggestions[0].BaseText : null; bool haveExactMatch = nearestMatch == TranslationText.Text; if (havePreviousTextKey) { // Store the previous text key with the IsDummy flag at the first position suggestions.Insert(0, new SuggestionViewModel(null) { TextKey = prevTextKey, BaseText = "(previous text key)", IsDummy = true }); } // Show the suggestions list if there is at least one other text key and at least two // list items to select from (or the nearest text is not an exact match) //if (haveOtherKeys && // (suggestions.Count > 1 || !haveExactMatch)) //{ OtherKeysLabel.Visibility = Visibility.Visible; OtherKeysList.Visibility = Visibility.Visible; //} //else //{ // OtherKeysLabel.Visibility = Visibility.Collapsed; // OtherKeysList.Visibility = Visibility.Collapsed; //} OtherKeysList.Items.Clear(); foreach (var suggestion in suggestions) { OtherKeysList.Items.Add(suggestion); } // Preset the text key input field if requested and possible if (setTextKey) { if (haveExactMatch) { if (havePreviousTextKey) { // There's the previous key and more suggestions (with an exact match), take // the first suggestion TextKeyText.Text = suggestions[1].TextKey; OtherKeysList.SelectedIndex = 1; } else { // There's only other suggestions (with an exact match), take the first one TextKeyText.Text = suggestions[0].TextKey; OtherKeysList.SelectedIndex = 0; } AutoSelectKeyText(); } else if (havePreviousTextKey) { // There's only the previous key, take that TextKeyText.Text = prevTextKey; OtherKeysList.SelectedIndex = 0; AutoSelectKeyText(); } // else: We have no exact match to suggest at the moment, leave the text key empty } }
private static void FocusAndSelect(TextBox textBox) { Keyboard.Focus(textBox); textBox.SelectAll(); }
/// <summary> /// Constructor</summary> /// <param name="adornedElement">Adorned element</param> public EditableTextBlockAdorner(TextBlock adornedElement) : base(adornedElement) { m_collection = new VisualCollection(this); m_textBox = new TextBox(); m_textBox.FontSize = adornedElement.FontSize; m_textBox.FontFamily = adornedElement.FontFamily; m_textBox.FontStretch = adornedElement.FontStretch; m_textBox.FontStyle = adornedElement.FontStyle; m_textBox.FontWeight = adornedElement.FontWeight; m_textBox.Width = adornedElement.Width; m_textBox.Height = adornedElement.Height; m_textBox.HorizontalAlignment = HorizontalAlignment.Left; m_textBox.VerticalAlignment = VerticalAlignment.Top; m_textBox.Padding = new Thickness(0); m_textBlock = adornedElement; Binding binding = new Binding("Text") { Source = adornedElement }; m_textBox.SetBinding(TextBox.TextProperty, binding); m_textBox.AcceptsReturn = false; m_textBox.AcceptsTab = false; //_textBox.MaxLength = adornedElement.MaxLength; m_textBox.KeyUp += TextBox_KeyUp; m_textBox.LostFocus += TextBox_LostFocus; m_textBox.SelectAll(); m_collection.Add(m_textBox); }
/// <summary> /// Двойной клик по текстовому полю /// </summary> /// <param name="source"></param> public void TBoxDoubleClick(TextBox source) { source.SelectAll(); }
public static void bindTextBox(TextBox textBox, string name) { var binding = new Binding(name); binding.Source = settings; textBox.SetBinding(TextBox.TextProperty, binding); textBox.GotFocus += (sender, e) => { textBox.SelectAll(); }; }
public void selectAllText(TextBox textBox) { textBox.SelectAll(); }
//############################################################ //################ Spin Box ################## //############################################################ private void ResetText(TextBox tb) { tb.Text = 1 < Minimum ? Minimum.ToString() : "1"; tb.SelectAll(); }
/// <summary> /// Calcular el producto /// </summary> /// <param name="sender"></param> private void CalcularProducto(object sender) { AlmacenCierreDiaInventarioInfo seleccion = (AlmacenCierreDiaInventarioInfo)gridProductosInventario.SelectedItem; TextBox text = (TextBox)sender; if (seleccion != null && text.Text != "") { text.Text = text.Text.Replace(" ", ""); if (ValidarDecimal(text.Text)) { var cantidad = decimal.Parse(text.Text.Trim(), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); if (cantidad > 0) { foreach (var almacenCierreDiaInventarioInfo in datosGrid.Where(almacenCierreDiaInventarioInfo => seleccion.ProductoID == almacenCierreDiaInventarioInfo.ProductoID)) { almacenCierreDiaInventarioInfo.ImporteReal = almacenCierreDiaInventarioInfo.PrecioPromedio * cantidad; almacenCierreDiaInventarioInfo.FolioAlmacen = long.Parse(txtFolio.Text); almacenCierreDiaInventarioInfo.CantidadReal = cantidad; almacenCierreDiaInventarioInfo.Observaciones = txtObservaciones.Text; btnGuardar.IsEnabled = true; break; } } else { foreach (var almacenCierreDiaInventarioInfo in datosGrid) { if (seleccion.ProductoID == almacenCierreDiaInventarioInfo.ProductoID) { almacenCierreDiaInventarioInfo.ImporteReal = 0; almacenCierreDiaInventarioInfo.CantidadReal = 0; break; } } } } else { index = gridProductosInventario.SelectedIndex; SkMessageBox.Show(Application.Current.Windows[ConstantesVista.WindowPrincipal], Properties.Resources.CierreDiaInventario_CantidadInsertadaError, MessageBoxButton.OK, MessageImage.Warning); gridProductosInventario.CurrentCell = new DataGridCellInfo( gridProductosInventario.Items[index], gridProductosInventario.Columns[4]); gridProductosInventario.BeginEdit(); gridProductosInventario.SelectedIndex = index; text.SelectAll(); return; } } index = gridProductosInventario.SelectedIndex; gridProductosInventario.ItemsSource = null; gridProductosInventario.ItemsSource = datosGrid; gridProductosInventario.Focus(); if (gridProductosInventario.Items.Count > (index + 1)) { gridProductosInventario.CurrentCell = new DataGridCellInfo( gridProductosInventario.Items[index + 1], gridProductosInventario.Columns[4]); gridProductosInventario.BeginEdit(); gridProductosInventario.SelectedIndex = index + 1; } else { btnGuardar.Focus(); } text.Focus(); text.SelectAll(); }
private static void FocusTextBox(TextBox nextTextbox) { nextTextbox.Focus(); nextTextbox.SelectAll(); }
private void SelectText(TextBox box, bool selectAll, string text) { ControlFocus.GiveFocus(box, delegate { if (selectAll) box.SelectAll(); else if (!string.IsNullOrEmpty(text)) { int pos = box.Text.IndexOf(text); if (pos > 0 && box.Text.Contains(text)) box.Select(pos, text.Length); } }); }
void ChangeTextBoxName(TextBox sender) { if (sender.IsEnabled == false && m_EditedTextBox == null) { m_EditedTextBox = sender; sender.IsEnabled = true; sender.LostFocus += new RoutedEventHandler(TextBox_LostFocus); m_TextStartEditText = sender.Text; sender.SelectAll(); sender.Focus(); } }
//discards non digits, prepares IPMaskedBox for textchange. private void handleTextInput(TextBox currentBox, TextBox rightNeighborBox, TextCompositionEventArgs e) { if (!char.IsDigit(Convert.ToChar(e.Text))) { e.Handled = true; SystemSounds.Beep.Play(); return; } if (currentBox.Text.Length == 3 && currentBox.SelectionLength == 0) { e.Handled = true; SystemSounds.Beep.Play(); if (currentBox != fourthBox) { rightNeighborBox.Focus(); rightNeighborBox.SelectAll(); } } }
private void ManipulateValue(TextBox tb, ValueManipulator ValMan) { if (tb.get_HMSType() == HMSType.t || tb.get_HMSType() == HMSType.tt) { AM_PM_Change(tb); return; } int NewValue; if (int.TryParse(tb.Text, out NewValue)) ValMan(tb, NewValue); tb.Focus(); tb.SelectAll(); }
//checks for backspace, arrow and decimal key presses and jumps boxes if needed. //returns true when key was matched, false if not. private bool checkJumpRight(TextBox currentBox, TextBox rightNeighborBox, KeyEventArgs e) { switch (e.Key) { case Key.Right: if (currentBox.CaretIndex == currentBox.Text.Length || currentBox.Text == "") { jumpRight(rightNeighborBox, e); } return true; case Key.OemPeriod: case Key.Decimal: case Key.Space: jumpRight(rightNeighborBox, e); rightNeighborBox.SelectAll(); return true; default: return false; } }
void AM_PM_Handle(TextBox tb) { bool IsAm; if (tb.get_HMSType() == HMSType.tt) IsAm = (tb.Text == SystemDateInfo.AMDesignator); else // tb.get_HMSType() == HMSType.t IsAm = (tb.Text == SystemDateInfo.AMDesignator[TimeCtrlExtensions.Get_t_Idx()].ToString()); Value = Value.Reset_AM_PM_Time(IsAm); tb.SelectAll(); }
private TextBox CreateTextBox( EditableTextBlock adornedElement ) { var textBox = new TextBox(); Binding binding = new Binding( "Text" ) { Source = adornedElement, UpdateSourceTrigger = UpdateSourceTrigger.Explicit }; textBox.SetBinding( TextBox.TextProperty, binding ); textBox.AcceptsReturn = true; textBox.MaxLength = adornedElement.MaxLength; textBox.KeyUp += myTextBox_KeyUp; textBox.LostFocus += myTextBox_LostFocus; textBox.SelectAll(); return textBox; }
static void SelectAllWhenFocused(TextBox textBox) => textBox.GotKeyboardFocus += (s, e) => textBox.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => textBox.SelectAll()));
private void selectAllText(TextBox aTextBox) { aTextBox.SelectAll(); }
static void Main(string[] args) { var c = new JSCSolutionsNETCarouselCanvas { CloseOnClick = false }; c.HideSattelites(); //c.Container.Effect = new DropShadowEffect(); //c.Container.BitmapEffect = new DropShadowBitmapEffect(); //.MoveTo(0, ImageCarouselCanvas.DefaultHeight - 96).SizeTo(ImageCarouselCanvas.DefaultWidth, 96); var cc = new Canvas(); // http://cloudstore.blogspot.com/2008/05/creating-custom-window-style.html var wcam = new Window(); wcam.Background = Brushes.Transparent; wcam.WindowStyle = WindowStyle.None; wcam.ResizeMode = ResizeMode.NoResize; wcam.SizeTo(200, 200); wcam.AllowsTransparency = true; //wcam.Opacity = 0.5; wcam.ShowInTaskbar = false; wcam.Cursor = Cursors.Hand; wcam.Focusable = false; wcam.Topmost = true; var w = cc.ToWindow(); w.SizeToContent = SizeToContent.Manual; //w.SizeTo(400, 400); //w.ToTransparentWindow(); // http://blog.joachim.at/?p=39 // http://blogs.msdn.com/changov/archive/2009/01/19/webbrowser-control-on-transparent-wpf-window.aspx // http://blogs.interknowlogy.com/johnbowen/archive/2007/06/20/20458.aspx w.AllowsTransparency = true; w.WindowStyle = System.Windows.WindowStyle.None; w.Focusable = false; //w.Background = new SolidColorBrush(Color.FromArgb(0x20, 0, 0, 0)); w.Background = Brushes.Transparent; w.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; w.Topmost = true; //w.ShowInTaskbar = false; var winfoc = new Canvas(); var winfo = winfoc.ToWindow(); winfo.AllowsTransparency = true; winfo.ShowInTaskbar = false; winfo.WindowStyle = WindowStyle.None; //winfo.Background = Brushes.Transparent; winfo.Background = Brushes.Red; winfo.Opacity = 0.3; winfo.ResizeMode = ResizeMode.NoResize; winfo.SizeToContent = SizeToContent.Manual; winfo.Topmost = true; // http://www.squidoo.com/youtubehd var NextInputModeEnabled = false; var NextInputModeKeyDownEnabled = false; Action <Key> NextInputModeKeyDown = delegate { }; var CommandKeysEnabled = false; #region TopicText var TopicText = new System.Windows.Controls.TextBox { //IsReadOnly = true, Background = Brushes.Transparent, BorderThickness = new System.Windows.Thickness(0), Foreground = Brushes.White, Effect = new DropShadowEffect(), Text = "JSC C# Foo Bar", //TextDecorations = TextDecorations.Underline, FontFamily = new FontFamily("Verdana"), FontSize = 24, TextAlignment = System.Windows.TextAlignment.Right }; #endregion #region KeyDown InterceptKeys.KeyDown += key => { if (key == Key.LeftShift) { //w.Background = new SolidColorBrush(Color.FromArgb(2, 0, 0, 0)); //w.MakeInteractive(true); NextInputModeEnabled = true; } else { if (NextInputModeEnabled || NextInputModeKeyDownEnabled) { NextInputModeKeyDownEnabled = false; NextInputModeKeyDown(key); } NextInputModeEnabled = false; } }; #endregion #region KeyUp InterceptKeys.KeyUp += key => { if (key == Key.CapsLock) { CommandKeysEnabled = !CommandKeysEnabled; TopicText.IsReadOnly = CommandKeysEnabled; TopicText.Select(0, 0); } if (key == Key.LeftShift) { NextInputModeKeyDownEnabled = false; } else { } NextInputModeEnabled = false; }; #endregion var s = 7; var ThumbnailSize = 0.4; var CaptionBackgroundHeight = 24; #region UpdateChildren Action UpdateChildren = delegate { if (w.ActualWidth == 0) { return; } var ss = s; var ss2 = 0; Console.WriteLine( new { w.Left, w.Top }); winfo.MoveTo(w.Left, w.Top).SizeTo(w.ActualWidth, w.ActualHeight); if (ThumbnailSize == 1) { wcam.Background = Brushes.Black; ss = 0; var qw = w.ActualWidth - ss * 2; var qh = w.ActualHeight - ss * 2; // no status bars or menues please :) wcam.MoveTo( w.Left + ss + ss2, w.Top + (w.ActualHeight - qh * ThumbnailSize - ss) - ss2 ).SizeTo( qw * ThumbnailSize, qh * ThumbnailSize ); } else { wcam.Background = Brushes.Transparent; //if (w.WindowState == WindowState.Maximized) //{ // ss2 = s; //} var qw = w.ActualWidth - ss * 2; var qh = w.ActualHeight - ss * 2; wcam.MoveTo(w.Left + ss + ss2, w.Top + (w.ActualHeight - qh * ThumbnailSize - ss) - ss2).SizeTo(qw * ThumbnailSize, qh * ThumbnailSize); } }; #endregion w.LocationChanged += delegate { UpdateChildren(); }; var Borders = Enumerable.Range(1, s * 2).Reverse().Select( Width => new { Width = Width * 2, Left = new Rectangle { Fill = Brushes.Black, Opacity = 0.06 }.MoveTo(0, 0).AttachTo(winfoc), Right = new Rectangle { Fill = Brushes.Black, Opacity = 0.06 }.MoveTo(0, 0).AttachTo(winfoc), Bottom = new Rectangle { Fill = Brushes.Black, Opacity = 0.03 }.MoveTo(0, 0).AttachTo(winfoc), Top = new Rectangle { Fill = Brushes.Black, Opacity = 0.11 }.MoveTo(0, 0).AttachTo(winfoc) } ).ToArray(); var CaptionBackgroundOverlay = new Rectangle { Fill = Brushes.Black, Opacity = 0.02, }.AttachTo(cc); var CaptionSysMenuOverlay = new Rectangle { Fill = Brushes.Black, Opacity = 0.02, }.AttachTo(cc).SizeTo(CaptionBackgroundHeight * 4, CaptionBackgroundHeight); var ExtraBorderTop = new Rectangle { Fill = Brushes.Black, Opacity = 0.0, }.AttachTo(winfoc); var ExtraBorderBottom = new Rectangle { Fill = Brushes.Black, Opacity = 0.0, }.AttachTo(winfoc); var CaptionClose = new TextBox { Foreground = Brushes.Red, FontFamily = new FontFamily("Webdings"), Text = "r", Background = Brushes.Transparent, BorderThickness = new Thickness(0), TextAlignment = System.Windows.TextAlignment.Center, Opacity = 0.5 }.AttachTo(winfoc); var CaptionText = new System.Windows.Controls.TextBox { IsReadOnly = true, Background = Brushes.Transparent, BorderThickness = new System.Windows.Thickness(0), Foreground = Brushes.White, Effect = new System.Windows.Media.Effects.DropShadowEffect(), Text = "jsc-solutions.net", //TextDecorations = TextDecorations.Underline, FontFamily = new FontFamily("Verdana"), FontSize = 16, TextAlignment = System.Windows.TextAlignment.Right } .AttachTo(winfoc); TopicText.AttachTo(winfoc); #region SetCaption Action <string> SetCaption = text => { if (string.IsNullOrEmpty(text)) { CaptionText.Text = "jsc-solutions.net"; } else { CaptionText.Text = text + " | jsc-solutions.net"; } }; #endregion c.AttachContainerTo(winfoc); var ExtraBorderSize = 0.10; var Intro = new PromotionBrandIntro.ApplicationCanvas().AttachTo(winfoc); Intro.Opacity = 0; #region SizeChanged Action SizeChanged = delegate { Intro.SizeTo(w.ActualWidth, w.ActualHeight); //ink.SizeTo(w.ActualWidth, w.ActualHeight - CaptionBackgroundHeight); var CaptionWidth = 200; CaptionBackgroundOverlay.MoveTo(w.ActualWidth - CaptionWidth, 0).SizeTo(CaptionWidth, CaptionBackgroundHeight); ExtraBorderTop.MoveTo(0, 0).SizeTo(w.ActualWidth, w.ActualHeight * ExtraBorderSize); ExtraBorderBottom.MoveTo(0, w.ActualHeight * (1 - ExtraBorderSize)).SizeTo(w.ActualWidth, w.ActualHeight * ExtraBorderSize); TopicText.MoveTo( 0, w.ActualHeight - 48 ).SizeTo(w.ActualWidth - 48, 48); if (c != null) { c.MoveContainerTo(-200 + 42, -200 + 38); } Borders.WithEach(k => k.Left.MoveTo(0, 0).SizeTo(k.Width, w.ActualHeight)); Borders.WithEach(k => k.Right.MoveTo(w.ActualWidth - k.Width, 0).SizeTo(k.Width, w.ActualHeight)); Borders.WithEach(k => k.Bottom.MoveTo(0, w.ActualHeight - k.Width).SizeTo(w.ActualWidth, k.Width)); Borders.WithEach(k => k.Top.MoveTo(0, 0).SizeTo(w.ActualWidth, k.Width)); CaptionText.MoveTo(0, 2).SizeTo(w.ActualWidth - CaptionBackgroundHeight, 32); CaptionClose.MoveTo(w.ActualWidth - CaptionBackgroundHeight, s).SizeTo(CaptionBackgroundHeight - s, CaptionBackgroundHeight - s); UpdateChildren(); }; #endregion w.SizeChanged += delegate { SizeChanged(); }; w.StateChanged += delegate { if (w.WindowState == WindowState.Maximized) { w.WindowState = WindowState.Normal; } SizeChanged(); }; #region GetWindows Func <IEnumerable <Internal.Window> > GetWindows = delegate { var windows = new List <Internal.Window>(); Internal.EnumWindows( (IntPtr hwnd, int lParam) => { if (new WindowInteropHelper(wcam).Handle != hwnd && (Internal.GetWindowLongA(hwnd, Internal.GWL_STYLE) & Internal.TARGETWINDOW) == Internal.TARGETWINDOW ) { StringBuilder sb = new StringBuilder(100); Internal.GetWindowText(hwnd, sb, sb.Capacity); windows.Add( new Internal.Window { Handle = hwnd, Title = sb.ToString() } ); } return(true); //continue enumeration } , 0); return(windows.OrderBy(k => k.Title)); }; #endregion var ResetThumbnailSkip = 0; Func <Internal.Window> GetCurrentThumbnail = () => GetWindows().AsCyclicEnumerable().Skip(ResetThumbnailSkip).First(); #region AnimationCompleted Intro.AnimationCompleted += delegate { if (c == null) { c = new JSCSolutionsNETCarouselCanvas { CloseOnClick = false }.AttachContainerTo(winfoc); c.HideSattelites(); CaptionClose.Show(); SizeChanged(); } }; #endregion wcam.SourceInitialized += delegate { { wcam.MakeInteractive(false); UpdateChildren(); } var thumb = IntPtr.Zero; ResetThumbnailSkip = GetWindows().Where( k => k.Title.Contains("Chrome") || k.Title.Contains("Studio") || k.Title.Contains("Minefield") ).TakeWhile(k => k.Handle != Internal.GetForegroundWindow()).Count(); #region ResetThumbnail Action ResetThumbnail = delegate { GetCurrentThumbnail().With( shadow => { //t.Text = shadow.Title; if (thumb != IntPtr.Zero) { Internal.DwmUnregisterThumbnail(thumb); } int i = Internal.DwmRegisterThumbnail( new WindowInteropHelper(wcam).Handle, shadow.Handle, out thumb); #region UpdateThumbnail Action UpdateThumbnail = delegate { if (thumb != IntPtr.Zero) { Internal.PSIZE size; Internal.DwmQueryThumbnailSourceSize(thumb, out size); Internal.DWM_THUMBNAIL_PROPERTIES props = new Internal.DWM_THUMBNAIL_PROPERTIES(); props.fVisible = true; props.dwFlags = Internal.DWM_TNP_VISIBLE | Internal.DWM_TNP_RECTDESTINATION | Internal.DWM_TNP_OPACITY | Internal.DWM_TNP_SOURCECLIENTAREAONLY; props.opacity = (byte)((byte)(0x7F) + (byte)((0x80) * (ThumbnailSize))); props.rcDestination = new Internal.Rect(0, 0, (int)wcam.ActualWidth, (int)wcam.ActualHeight); props.fSourceClientAreaOnly = true; if (size.x < wcam.ActualWidth) { props.rcDestination.Right = props.rcDestination.Left + size.x; props.rcDestination.Left += ((int)wcam.ActualWidth - size.x) / 2; props.rcDestination.Right += ((int)wcam.ActualWidth - size.x) / 2; } if (size.y < wcam.ActualHeight) { props.rcDestination.Bottom = props.rcDestination.Top + size.y; props.rcDestination.Top += ((int)wcam.ActualHeight - size.y) / 2; props.rcDestination.Bottom += ((int)wcam.ActualHeight - size.y) / 2; } Internal.DwmUpdateThumbnailProperties(thumb, ref props); } }; #endregion (1000 / 15).AtInterval(UpdateThumbnail); wcam.SizeChanged += delegate { UpdateThumbnail(); }; } ); }; #endregion ResetThumbnail(); NextInputModeKeyDown += key => { if (key == Key.RightShift) { NextInputModeKeyDownEnabled = true; if (c != null) { CaptionClose.Hide(); c.AtClose += delegate { c.OrphanizeContainer(); }; c.Close(); c = null; } Intro.Background = Brushes.Transparent; Intro.Overlay.Opacity = 1; Intro.FadeIn( delegate { 2000.AtDelay(Intro.PrepareAnimation()); } ); } if (!CommandKeysEnabled) { if (key == Key.F2) { w.Activate(); TopicText.Focusable = true; TopicText.Focus(); TopicText.SelectAll(); } return; } if (key == Key.Right) { if (w.IsActive) { GetCurrentThumbnail().Activate(); } else { NextInputModeKeyDownEnabled = true; ResetThumbnailSkip = GetWindows().TakeWhile(k => k.Handle != Internal.GetForegroundWindow()).Count(); ResetThumbnail(); } } if (key == Key.Up) { NextInputModeKeyDownEnabled = true; if (ThumbnailSize < 0.3) { ThumbnailSize = 0.3; } else if (ThumbnailSize < 0.5) { ThumbnailSize = 0.5; } else if (ThumbnailSize < 1) { ThumbnailSize = 1; } else { if (c != null) { CaptionClose.Hide(); c.AtClose += delegate { c.OrphanizeContainer(); }; c.Close(); c = null; } } UpdateChildren(); } if (key == Key.Down) { NextInputModeKeyDownEnabled = true; if (c == null) { c = new JSCSolutionsNETCarouselCanvas { CloseOnClick = false }.AttachContainerTo(winfoc); CaptionClose.Show(); } else if (ThumbnailSize > 0.5) { ThumbnailSize = 0.5; } else if (ThumbnailSize > 0.3) { ThumbnailSize = 0.3; } else if (ThumbnailSize == 0.3) { ThumbnailSize = 0; } SizeChanged(); } if (key == Key.Left) { if (w.IsActive) { NextInputModeKeyDownEnabled = true; if (ExtraBorderTop.Opacity == 1) { ExtraBorderTop.Opacity = 0; ExtraBorderBottom.Opacity = 0; } else { ExtraBorderTop.Opacity = 1; ExtraBorderBottom.Opacity = 1; } } } }; }; winfo.SourceInitialized += delegate { winfo.MakeInteractive(false); }; w.SourceInitialized += delegate { // http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/61e93dca-e24c-4953-9719-22ce3f705353 Matrix m = PresentationSource.FromVisual(w).CompositionTarget.TransformToDevice; double dx = m.M11; double dy = m.M22; w.SizeTo(1280 / dx, 768 / dy); w.MoveTo(8, 0); SizeChanged(); wcam.Owner = w; winfo.Owner = w; wcam.Show(); winfo.Show(); HwndSource hwndSource = (HwndSource)HwndSource.FromVisual(w); hwndSource.AddHook( (IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handeled) => { if (msg == 0x0084) // WM_NCHITTEST { //http://agsmith.wordpress.com/2008/09/16/hit-testing-in-wpf/ var p = new { cx = w.ActualWidth - (Internal.LOWORD(lParam) - w.Left), cy = w.ActualHeight - (Internal.HIWORD(lParam) - w.Top), x = Internal.LOWORD(lParam) - w.Left, y = Internal.HIWORD(lParam) - w.Top }; CaptionText.Text = p.ToString(); handeled = true; return((IntPtr)HitTestValues.HTCAPTION); // HTCAPTION if (false) { if (p.x < s) { if (p.y < s) { return((IntPtr)HitTestValues.HTTOPLEFT); // HTCAPTION } } if (p.x < CaptionBackgroundHeight) { if (p.y < CaptionBackgroundHeight) { return((IntPtr)HitTestValues.HTSYSMENU); // HTCAPTION } } if (p.cx < CaptionBackgroundHeight) { if (p.y < CaptionBackgroundHeight) { return((IntPtr)HitTestValues.HTCLOSE); // HTCAPTION } } if (p.cx < s) { if (p.cy < s) { return((IntPtr)HitTestValues.HTBOTTOMRIGHT); // HTCAPTION } } if (p.cx < s) { if (p.y < s) { return((IntPtr)HitTestValues.HTTOPRIGHT); // HTCAPTION } } if (p.x < s) { if (p.cy < s) { return((IntPtr)HitTestValues.HTBOTTOMLEFT); // HTCAPTION } } if (p.x < s) { return((IntPtr)HitTestValues.HTLEFT); // HTCAPTION } if (p.y < s) { return((IntPtr)HitTestValues.HTTOP); // HTCAPTION } if (p.cx < s) { return((IntPtr)HitTestValues.HTRIGHT); // HTCAPTION } if (p.cy < s) { return((IntPtr)HitTestValues.HTBOTTOM); // HTCAPTION } if (p.y < CaptionBackgroundHeight) { return((IntPtr)HitTestValues.HTCAPTION); // HTCAPTION } return((IntPtr)HitTestValues.HTTRANSPARENT); // HTCAPTION } } return(IntPtr.Zero); } ); }; InterceptKeys.InternalMain( Rehook => { w.Deactivated += delegate { TopicText.Focusable = false; }; w.Activated += delegate { //TopicText.Focus(); Rehook(); }; w.ShowDialog(); } ); }
/// <summary> /// Sets the window to accept user input to start a new <see cref="Timer"/>. /// </summary> /// <param name="textBoxToFocus">The <see cref="TextBox"/> to focus. The default is <see cref="TimerTextBox"/>. /// </param> private void SwitchToInputMode(TextBox textBoxToFocus = null) { this.Mode = TimerWindowMode.Input; this.TimerTextBox.Text = this.LastTimerStart != null ? this.LastTimerStart.ToString() : string.Empty; textBoxToFocus = textBoxToFocus ?? this.TimerTextBox; textBoxToFocus.SelectAll(); textBoxToFocus.Focus(); this.EndAnimationsAndSounds(); this.UpdateBoundControls(); }
private void SetTextValue(TextBox tb, int value) { tb.Focus(); tb.Text = value.ToString(); tb.SelectAll(); }