tags:

views:

79

answers:

2

Hi,

I have a small problem. After making a hex mask, I can not copy/paste with CTRL C/V. If I right click in the textbox I can paste. But I would like to be able to just press CTRL V.

If I delete the hex mask, CTRL C/V works fine.

Here is a bit of the code:

private void maskedTextBox1(Object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
        // this will allow a-f, A-F, 0-9, "," 
        if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "^[0-9a-fA-F,V,C,'\b']+$"))
            {
                e.Handled = true;
            }

        // if keychar == 13this ill allow <ENTER>
        if (e.KeyChar == (char)13)
            {
            button1_Click(sender, e);
            }
        // I thought I could fix it with the lines below but it doesnt work
       /* if (e.KeyChar == (char)22)
        {
            // <CTRL + C> 
            e.Handled = true;
        }
        if (e.KeyChar == (char)03)
        {
            // is <CTRL + V>
            e.Handled = true;
        }*/
        //MessageBox.Show(((int)e.KeyChar).ToString());
    }

Could someone give me some hints, Please?

A: 

The MaskedTextBox might block the CTRL-V call (otherwise you could easily circumvent the mask). Personally, I wouldn't use a masked textbox but validate the input seperately, and alert the user if there is a problem with the input. The MaskedTextBox has drawbacks in general use, as it isn't a normal component the user is used to, a user is more used to being told that an input was wrong.

Femaref
+1  A: 

You need to catch these keystrokes with a KeyDown event handler, not KeyPressed. KeyPressed is only raised for typing keys.

A MaskedTextBox is not ideal here, you can also do it with a regular TextBox. Use the Validating event to format the number and check for range. For example:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
        bool ok = e.KeyChar == 8;  // Backspace
        if ("0123456789ABCDEF".Contains(char.ToUpper(e.KeyChar))) ok = true;
        if (!ok) e.Handled = true;
    }

    private void textBox1_Validating(object sender, CancelEventArgs e) {
        int value;
        if (textBox1.Text.Length > 0) {
            if (!int.TryParse(this.textBox1.Text, System.Globalization.NumberStyles.HexNumber, null, out value)) {
                this.textBox1.SelectAll();
                e.Cancel = true;
            }
            else {
                textBox1.Text = value.ToString("X8");
            }
        }
    }
Hans Passant
Thanks Hans, I'll try your solution