简体   繁体   中英

How to register mouse event from a different class

I have a class which trying to register an event in another class.

In class AI have a method as shown below:

 public void Mouse_Down(object sender, MouseEventArgs e)
        {

        }

I am registering the event in class B like so:

            ClassA classA = new ClassA();
            classA.MouseDown += new MouseEventHandler(classA.Mouse_Down);

When click nothing is happening. Does anyone know what the problem could be.

Assuming you want to handle the event raised by ClassB :

You are registering the event for ClassA 's event, not ClassB 's. The fact that you're doing it from class b doesn't mean anything.


Assuming you do want to handle the event raised by ClassA :

One possibility is that a different instance of ClassA is triggering the event, not the one who's event is handled.

ClassA classA = new ClassA();

The above creates a new instance of classA. If it's not this one that raises an event, then you won't get your method called.

Set a breakpoint at the event triggering code (of classA) and check your EventHandlers collection. I bet there is no one registered and you're messing with classA instances.

It is also possible that you will never get your breakpoint, which means that your event is not fired.

Anyway the thing that you want to do looks a little weird for me.

Edit:

Have you tried to register a different method to the same event 'in normal way' (ex. from a ClassA constructor)? If you don't have access to event triggering code, that is to best way to check if there are proper handlers registered, at the moment of event being fired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM