Search code examples
wpf

gotfocus and KeyEventArgs


        private void TextBox27_GotFocus(object sender, RoutedEventArgs e)
        {
            Stil53.Begin();
            TextBox27.Select(TextBox27.Text.Length, 0);
            Takvim_Kapat();
            KeyEventHandler mhth = new KeyEventHandler(TextBox27_PreviewKeyUp); <=////this
        }

        private void TextBox27_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            Listelemeler.Para_Birimi_Noktalama(TextBox27, e);
        }

In the gotfocus incident I'm trying to trigger the KeyEventArgs event. How can I achieve this? Can you give me an idea? thank you in advance

In the gotfocus incident I'm trying to trigger the KeyEventArgs event. How can I achieve this? Can you give me an idea? thank you in advance


Solution

  • a sample of solution maybe i have no checked all your validation, but you have an idea how to do:

        private void TextBox27_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            TextBox textBox = (TextBox)sender;
    
            // Check if there is already a comma present in the TextBox's text
            bool commaExists = textBox.Text.Contains(",");
            int maxLength = 9;
    
            // check if key del or back is pressed
            if(e.Key == Key.Delete || e.Key == Key.Back)
            {
                return;
            }
    
            if (e.Key == Key.Decimal || e.Key == Key.OemPeriod || e.Key == Key.OemComma)
            {
                if (!commaExists && textBox.Text.Length < maxLength)
                {
                    // Replace dot with comma
                    int caretIndex = textBox.CaretIndex;
                    textBox.Text = textBox.Text.Insert(caretIndex, ",");
    
                    // Move caret after the comma
                    textBox.CaretIndex = caretIndex + 1;
    
                    // Mark the event as handled
                    e.Handled = true;
                }
                else
                {
                    // Mark the event as handled to prevent the dot from being entered
                    e.Handled = true;
                }
            }
            else if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
            {
                // Check if adding a new character would exceed the maximum length
                if (textBox.Text.Length >= maxLength )
                {
                    // Mark the event as handled to prevent additional characters
                    e.Handled = true;
                }
            }
            else
            {
                // If the pressed key is not a number, a dot, or a comma, mark the event as handled
                e.Handled = true;
            }
        }