Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

winforms - How to call an event manually in C#?

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 tell me how to call an event manually, I can call usercontrol.keydown in textbox.keydown.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, events can only be raised from code within the control that declares the event. So, your user control has to declare the custom event KeyDown in order to raise it. You cannot, for instance, raise KeyDown on a TextBox contained by your user control. However, you can declare your own KeyDown, and attach a handler to the TextBox's KeyDown that will raise your own KeyDown.

Given this restriction, raising an event is easy:

public delegate void MyEventHandler(object sender, MyEventArgs e)

public event MyEventHandler MyEvent;

public void RaisesMyEvent()
{
   ...

   if(MyEvent != null) //required in C# to ensure a handler is attached
      MyEvent(this, new MyEventArgs(/*any info you want handlers to have*/));
}

Raising an event looks much like a method, because in essence that's what you're doing; you're calling one or more method delegates that are assigned to the MultiCast delegate behind the scenes of your event. Think of it as assigning a method to an ordinary named delegate (like if you'd omitted the "event" keyword from the definition) and calling it from inside your code. the only difference between a true event and that is that an event can have more than one handler delegate attached to it, and will invoke all of them when raised.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...