I have a USerControll in which i have a textbox. I use the usercontrol in my form, I want to do something when somebody presses enter on the textbox. how can I do it? if you
If you REALLY need to call an event manually, you can get the backing delegate, which is usually private. Use a .NET decompiler (such as ILSPY) to locate the Event's backing field, then use reflection to get the backing delegate.
Example: Getting the event DoWork from BackgroundWorker:
Decompile the BackgroundWorker class in ILSpy, and you see this:
public event DoWorkEventHandler DoWork
{
add
{
base.Events.AddHandler(doWorkKey, value);
}
remove
{
base.Events.RemoveHandler(doWorkKey, value);
}
}
So you need to find the Events member, and the doWorkKey field as a key.
Events is an EventHandlerList (public class) declared in class Component.
doWorkKey is a static field declared in class BackgroundWorker.
Then use reflection to get the delegate:
PropertyInfo property = backgroundWorker.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
EventHandlerList eventHandlerList = (EventHandlerList)property.GetValue(backgroundWorker, null);
FieldInfo doWorkField = backgroundWorker.GetType().GetField("doWorkKey", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy);
object doWorkKey = doWorkField.GetValue(null);
DoWorkEventHandler doWork = (DoWorkEventHandler)eventHandlerList[doWorkKey];
Now you have a delegate for the DoWork event, and can call it.
This same approach will also work for other Controls.
Note that using reflection to get private fields may break any time there is a new version of the code.