Mount Events in unreferenced assembly

Source: Internet
Author: User
Tags emit

There are two Assembly A,b declare an event in a (an event in a class), B does not refer to the Assembly, but want to hang the event in a. When a logic in a fire this event, B hangs the place of the event (B's handler) to do something.

Firefarevent is Assembly A, MainForm class exposes a someevent event, FireEvent button will Fire this event.

Attachfarevent is Assembly B, attachfareventform in Btnattachevent_click will hook Firefarevent someevent.

The Attachfarevent code is as follows:

is private void Btnattachevent_click (object sender, EventArgs e)
{
(assembly = = NULL | | firee Ventform = = null)
{
MessageBox.Show ("Please click the the the the the the the the the the the the the the". ");
return to;
07}
Type firefareventformtype = Fireeventform.gettype ();
Fareventeventinfo = firefareventformtype.getevent ("someevent");
Ten
EventHandler temphandler = new EventHandler (this.fareventhandler);//For dynamic method.
M Ethodinfo temphandlermethodinfo = Temphandler.method;


DynamicMethod dynamicmethod = new DynamicMethod (
"Bridgemethodforattachevent", Ty Peof (void),
new type[] {typeof (object), assembly. GetType ("Firefarevent.fareventargs")},
. GetType ());

ILGenerator il = dynamicmethod.getilgenerator ();

IL. Emit (OPCODES.NOP);
IL. Emit (OPCODES.LDARG_0);
IL. Emit (opcodes.ldarg_2);
IL. Emit (opcodes.ldarg_1);
IL. Emit (Opcodes.call, temphandlermethodinfo);
IL. Emit (OPCODES.NOP);
IL. Emit (Opcodes.ret);

Dynamicmethod.defineparameter (1, parameterattributes.in, "object");
to Dynamicmethod.definepar Ameter (2, parameterattributes.in, "E");

Fareventdelegate = dynamicmethod.createdelegate (fareventeventinfo.eventhandlertype);
FarEve Nteventinfo.addeventhandler (Fireeventform, fareventdelegate);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.