0

I have 2 textboxes in the form textbox1 and textbox2 (Yeah was pretty lazy) and the task of creating a copy and paste like function for the application (for practice reasons)

but I have no idea how the program will determine which textbox is currently the active one

    public partial class Form1 : Form
    {

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.F1) //Copy
        {

        }
        else if (e.KeyCode == Keys.F2) //Paste
        {

        }
    }
}
René Vogt
  • 43,056
  • 14
  • 77
  • 99

3 Answers3

0

You have to cast the sender to a TextBox and get its name or whatever identifies your textboxes. Do it responsibly, use as : var textBox = sender as TextBox and then check it for null

EDIT: the event handler must be assigned to both TextBoxelements not to the form

Alex
  • 3,689
  • 1
  • 21
  • 32
0

Possibly you have a question already got an answer.

Form.ActiveControl may be what you want.

Community
  • 1
  • 1
Shiv
  • 129
  • 2
  • 10
0

You can determine which TextBox is activated by using the ContainsFocus property:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    TextBox activeTextBox = textBox1.ContainsFocus 
                    ? textBox1
                    : (textBox2.ContainsFocus ? textBox2 : null);     

    if (e.KeyCode == Keys.F1) //Copy
    {

    }
    else if (e.KeyCode == Keys.F2) //Paste
    {

    }
}

Or alternatively the Form.ActiveControl property:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    TextBox activeTextBox = ActiveControl as TextBox;

    if (e.KeyCode == Keys.F1) //Copy
    {

    }
    else if (e.KeyCode == Keys.F2) //Paste
    {

    }
}
René Vogt
  • 43,056
  • 14
  • 77
  • 99