Search code examples
c#.netwinformspastemaskedtextbox

Winforms MaskedTextBox - Reformatting pasted text to match mask


I have a MaskedTextBox control that, in our case, is collecting social insurance (tax) numbers (without a ValidatingType though since the string representation including the mask literals). A social insurance number is 3 groups of 3 digits separated by dashes. Sometimes spaces may be typed or entered instead of the dashes.

The configuration of the textbox is:

  • Mask: 999-999-999
  • ValidationType: null / not required
  • SkipLiterals: true
  • CutCopyMaskFormat: IncludeLiterals (only relevant when cut/copy FROM textbox)
  • TextMaskFormat: IncludeLiterals

-- Let me know if there other properties that you think could be important!

Problem

When pasting the following tax number "450 622 097" because of the spaces it doesn't match the mask. So I end up with "450- 62-2 9" in the text box. Pasting "450-622-097" will successfully paste into the box.

I want to be able to intercept the paste event in order to possibly fix it up to replace the spaces with dashes.

Alternatively, could we make the mask accept dashes OR spaces (but always output dashes)?

Non-solutions

MaskInputRejected event - I can't seem to get a handle on what was originally input (i.e. what's being rejected) so as to compare it with what's sitting at the top of the Clipboard. It merely returns how it was rejected

Validating event - Already occurs after the mask has been applied. I.e. the value of "450- 62-2 9" is in the textbox now.

Use custom ValidatingType with static Parse function - Again, occurs after the mask has been applied.

Detecting Key-Down event - Then if key series is Ctrl-V then manually handle and pass in a cleaned up version of the clipboard text. Could work, but then what about paste via the right click context menu?

Any other ideas?


Solution

  • While this is a hammer solution, there are limitations to the mask string and i don't see another way around it. What you need is to capture the paste event and process the text before it gets in the textbox. See below a simplistic example

       class MyMaskedTextbox : MaskedTextBox
            {
                const int WM_PASTE = 0x0302;
    
                protected override void WndProc(ref Message m)
                {
                    switch (m.Msg)
                    {
                        case WM_PASTE:
                            if (Clipboard.ContainsText())
                            {
                                string text = Clipboard.GetText();
                                text = text.Replace(' ', '-');
    //put your processing here
                                Clipboard.SetText(text);
                            }
                            break;
                    }
                    base.WndProc(ref m);
                }
            }