0

How to copy or duplicate other controls events? I want to use other controls event in a new controls. Lets say i have a textboxes.

TextBox tbTemp = new TextBox ();
tbTemp.Keypress += new KeyPressEventHandler(some keypress); //I assigned some keypress event here & this works fine


TextBox tbNew = new TextBox ();//create new textbox and assign keypress events from existing textbox
tbNew.Keypress += tbTemp.Keypress; //This is not working. It says the event control.keypress can only appear on left hand side of +=

or

tbNew.Keypress += new KeyPressEventHandler(tbTemp.Keypress);//this is not working

Is there a way to capture other controls events? I need to capture or duplicate the tbTemp keypressEvent and assigned to new TextBox(tbNew)

Vincent
  • 145
  • 2
  • 11
  • Which keypress events do you exactly wish to capture? – tomerpacific Mar 23 '20 at 06:29
  • Your question is unclear. Do you want to subscribe single instance of function to KeyPress events of many controls? – Louis Go Mar 23 '20 at 06:32
  • lets say i have a textbox1 which already have a keypress events assigned. What i want is I create new a textbox2, i need to assign textbox2 keypress event from textbox1. Like textbox2.keypress=textbox1 keypress – Vincent Mar 23 '20 at 06:37
  • `tb1.KeyPress += AFunction; tb2.KeyPress += AFunction;` Is this want you want to achieve? – Louis Go Mar 23 '20 at 06:51
  • @LouisGo probably something like that, function that can duplicate some existing controls keypressEvent – Vincent Mar 23 '20 at 06:54
  • Your wording is confusing. If you want 4 controls fire event and run the same function. Just subscribe it for times, like my previous comment. Please edit you question and elaborate on what you want to achieve. – Louis Go Mar 23 '20 at 07:31

1 Answers1

0

I post this answer if your question is

"I have many textboxes, but if any of one "KeyPress" are fires, I want the same function handle it."

All you need to do is subscribe the same function OnKeyPress to different controls' events.

// This is the function
private void OnKeyPress( object sender, KeyPressEventArgs e )
{
    // Your implementation.
}


// Your constructor or where your subscribe event.
void Constructor()
{
 // This will work
    tbTemp += new System.Windows.Forms.KeyPressEventHandler(OnKeyPress);

    tbNew += new System.Windows.Forms.KeyPressEventHandler(OnKeyPress);
}

If this is not answering your question, please edit and explain what you want to achieve.

========

Your question was

I need to capture or duplicate the tbTemp keypressEvent and assigned to new TextBox(tbNew)

Each control has its own KeyPress event, you don't have to copy ( duplicate ) it. So "duplicate KeyPress event" is confusing.

Then I assume you do not want to "duplicate event" but "subscribe same event of controls to a single function."

Take a look at Understanding events and event handlers in C#

It should help for explain your question.

Louis Go
  • 2,213
  • 2
  • 16
  • 29