betaFlux
betaFlux

Reputation: 183

connect a single key event to the control that has focus

I have two textboxes, each with its own keypress event attached.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar == '\r')
    {
        e.Handled = true;
        // some other stuff
    }
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar == '\r')
    {
        e.Handled = true;
        // some other stuff
    }
}

Is there a way to connect the keypress event dynamically to the focused textbox?

EDIT:

Something like:

void KeyPress(object sender, KeyPressEventArgs e)
{
    foreach(Control c in this)
    {
        if(c == TextBox && c.Focused)
        {
            if(e.KeyChar == '\r')
            {
                // do something
            }
        }
    }
}

Upvotes: 0

Views: 39

Answers (1)

Benji_9989
Benji_9989

Reputation: 173

You can do that :

textBox1.KeyPress += new KeyPressEventHandler(textBox_KeyPress);
textBox2.KeyPress += new KeyPressEventHandler(textBox_KeyPress);

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar == '\r')
    {
        e.Handled = true;
        // some other stuff
        Console.WriteLine(((TextBox)sender).Name); //actual textbox name
    }
}

Upvotes: 2

Related Questions