pasting

using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace OnlyCapsNumbers
{
    public partial class MainWindow : Window
    {
        // ✅ Allowed chars: A–Z and digits
        private static readonly Regex AllowedRegex = new Regex("^[A-Z0-9]$");

        public MainWindow()
        {
            InitializeComponent();
        }

        // Block invalid typing
        private void txtInput_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = !AllowedRegex.IsMatch(e.Text);
        }

        // Sanitize pasted text (check each character)
        private void txtInput_Pasting(object sender, DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetDataPresent(DataFormats.Text))
            {
                string pasteText = (string)e.DataObject.GetData(DataFormats.Text);

                // keep only valid characters
                string filtered = new string(pasteText.Where(ch => AllowedRegex.IsMatch(ch.ToString())).ToArray());

                if (!string.IsNullOrEmpty(filtered))
                {
                    // insert sanitized text instead of raw paste
                    var tb = sender as TextBox;
                    tb.SelectedText = filtered;
                }

                e.CancelCommand(); // prevent default paste
            }
            else
            {
                e.CancelCommand();
            }
        }
    }
}

Comments

Popular posts from this blog

My work

OpenCV - Overview