Raising events from a custom class

  • Thread starter Thread starter Landley
  • Start date Start date
L

Landley

Hello All,

I am new to C# (and converting from VB.NET).

1. I am trying to create a class that has one method and one event. The
method's sole purpose is to raise the event.
2. ... then instantiate the class from another class (e.g. a Form) and call
the method on the first class.
3. ... then handle the event raised from the first class.

Simple you say! I haven't come across a simple example of this in any
documentation.

Can you help and prevent me from self harm?!

Landley
 
Landley said:
Hello All,
I am new to C# (and converting from VB.NET).
1. I am trying to create a class that has one method and one event. The
method's sole purpose is to raise the event.
2. ... then instantiate the class from another class (e.g. a Form) and call
the method on the first class.
3. ... then handle the event raised from the first class.
Simple you say! I haven't come across a simple example of this in any
documentation.
Can you help and prevent me from self harm?!

I just went through this myself. I found Microsoft's example to be the
most helpful after searching the web. It's nearly what you want plus
a bit of fat.

http://tinyurl.com/5qdwu
 
Thanks for your help.

I think I have been wrapped in cotton wool during my VB6 and VB.NET years.
Events and event handling are so easy to create and manipulate. C# seems so
long winded. I'll hang in there, as when I become more familiar with the
strategies, I am sure that I will be more enthusiatic about it.
 
Hi Landley,

It is possible that I didn't understand correctly the problem, but I don't
see any tricky part here

class Bar
{
publuic event FooEventHandler Foo;
public void RaiseFoo(FooEventArgs e)
{
if(Foo != null)
Foo(this, e);

}
}

Now the form can instantiate Bar class and call RiseFoo. whoever has
subscribed will receive the even.

The form has to expose the istance in order the other to subscribe. The next
is thing is the real sender of the event. Reference to it can be embeded in
the event args ot the sender can pass itself to the RaiseFoo method as a
paramter and the the event will be raised on its behalf.

WindowsForm uses similar model on its Control.InvokeOnClick, for example,
where one can make other control to raise Click event.
Other example would be IComponentChangeService and its OnComponentChnagXXX
method that raise ComponentChangXXX events
 
Back
Top