Focus on a single C # textbox

0

Good morning, I have a problem with my textbox. I have the focus for one in specific but when I try to diguitar in the others I am activated in which I have the focus. How can I make the textbox that I have focus only activate when I scan (because that's the only reason I'm using it)? This is my code.

 private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!txtescaner.Focused)
        {
            txtescaner.Focus();
            txtescaner.Text += e.KeyChar;
            // Move el cursor al final
            txtescaner.SelectionStart = txtescaner.Text.Length;

            if (Char.IsNumber(e.KeyChar) || (char.IsSymbol(e.KeyChar)))
            {
                e.Handled = false;

            }
            else if (Char.IsLetter(e.KeyChar))
            {
                MessageBox.Show("Solo se permiten numeros", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Handled = true;
                txtescaner.Clear();
                return;
            }
        }
    }

Thank you.

    
asked by use2105 05.12.2016 в 14:02
source

4 answers

1

It could work if you put the other text boxes in the if

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (txtbox.Focused || txtbox2.Focused || txtbox3.Focused)
        {
            txtescaner.Focus();
            txtescaner.Text += e.KeyChar;
            // Move el cursor al final
            txtescaner.SelectionStart = txtescaner.Text.Length;

            if (Char.IsNumber(e.KeyChar) || (char.IsSymbol(e.KeyChar)))
            {
                e.Handled = false;

            }
            else if (Char.IsLetter(e.KeyChar))
            {
                MessageBox.Show("Solo se permiten numeros", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Handled = true;
                txtescaner.Clear();
                return;
            }
        }
    }
    
answered by 05.12.2016 в 14:55
1

I think it's because of the if of the first line of code ( if (!txtescaner.Focused) ) there you are asking if that textbox is not in focus. Being false you enter and the second line is put in focus txtescaner.Focus(); You should remove the first if

    
answered by 05.12.2016 в 14:26
0

The event that handles the state of focus is called Form1_KeyPress, so it is possible that the error is that the event is thrown every time you press a key inside the form. (The event is launched at the form level).

Make sure the event is launched by the TextBox you owe.

    
answered by 05.12.2016 в 16:47
0

The event is at the form level, try to change it for the specific event of the texbox you want to validate so you will avoid launching the event in any control

Another option would be to use masks for validation

    
answered by 05.12.2016 в 20:14