简体   繁体   English

如何从其他类注册鼠标事件

[英]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: 在类AI中有一个方法如下所示:

 public void Mouse_Down(object sender, MouseEventArgs e)
        {

        }

I am registering the event in class B like so: 我正在B类注册活动,如下:

            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 : 假设您要处理ClassB引发的事件:

You are registering the event for ClassA 's event, not ClassB 's. 您正在为ClassA的活动注册活动,而不是ClassB的活动。 The fact that you're doing it from class b doesn't mean anything. 你从b级做这件事并不意味着什么。


Assuming you do want to handle the event raised by ClassA : 假设您确实想要处理ClassA引发的事件:

One possibility is that a different instance of ClassA is triggering the event, not the one who's event is handled. 一种可能性是ClassA的不同实例触发事件,而不是处理事件的事件。

ClassA classA = new ClassA();

The above creates a new instance of classA. 以上创建了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. 在事件触发代码(classA)中设置断点并检查EventHandlers集合。 I bet there is no one registered and you're messing with classA instances. 我敢打赌,没有人注册,你正在搞乱classA实例。

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)? 您是否尝试以“正常方式”向同一事件注册不同的方法(例如,来自ClassA构造函数)? 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. 如果您无法访问事件触发代码,那么在事件被触发时,最好的方法是检查是否注册了正确的处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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