First of all, have you considered MaskedTextBox instead? It can handle character filtering for you.
However, for the sake of this exercise, you might think of a solution along this line. This usage:
public Form1() { InitializeComponent(); FiltreTbx.AddTextBoxFilter(tbxSigné, double.MinValue, double.MaxValue, @"[^\d\,\;\.\-]"); }
This AddTextBoxFilter is a new static method that you call only once. It will add a TextChanged handler to the TextBox . This handler uses closure to store the previous Text in a text field.
Your static method has received an additional parameter to go through this previous text.
public class FiltreTbx { public static void AddTextBoxFilter(TextBox textbox, double tailleMini, double tailleMaxi, string carNonAutorisé) { string previousText = textbox.Text; textbox.TextChanged += delegate(object sender, EventArgs e) { textChanged(e, textbox, tailleMini, tailleMaxi, carNonAutorisé, previousText); previousText = textbox.Text; }; } static public void textChanged(EventArgs e, TextBox textbox, double tailleMini, double tailleMaxi, string carNonAutorisé, string previousText) {
I'm not sure what exactly tailleTextBox should do exactly, you did not include this source code, but I suspect that it applies the minimum and maximum values?
Alternative solution
If you want to process the Insert operation yourself before this happens, you will have to intercept the WM_PASTE message in the text box. One way to do this is to create a custom control:
using System; using System.Windows.Forms; class MyTextBox : TextBox { private const int WM_PASTE = 0x0302; protected override void WndProc(ref Message m) { if (m.Msg != WM_PASTE) {
If you define a class in a WinForms project, you can drag it into your form like any other control.