来自一个类的鼠标事件,我如何在另一个类中监听它?

时间:2012-05-07 17:29:16

标签: c#

我在表单上有一个UserControl, 当我在那个UserControl上的MouseMove时,我想在Form中做一些事情。

如何让表格“倾听”此事件?

我正在使用Visual C#,。Net framework 3.5,winforms

3 个答案:

答案 0 :(得分:4)

我认为你指的是使用控制或类似的东西。

您可以添加public event,并在检测到内部类事件时在类中触发它。

然后你必须在第二节课中订阅已发布的事件。

这是一个示例,以便您看到sintax:

    public class WithEvent
    {
        // this is the new published event
        public EventHandler<EventArgs> NewMouseEvent;

        // This handles the original mouse event of the inner class
        public void OriginalEventhandler(object sender, EventArgs e)
        {
            // this raises the published event (if susbcribedby any handler)
            if (NewMouseEvent != null)
            {
                NewMouseEvent(this, e);
            }
        }
    }

    public class Subscriber
    {
        public void Handler(object sender, EventArgs e)
        {
            // this is the second class handler
        }

        public void Subscribe()
        {
            WithEvent we = new WithEvent();
            // This is how you subscribe the handler of the second class
            we.NewMouseEvent += Handler;
        }

    }

答案 1 :(得分:1)

如果您正在谈论Windows Forms(问题尚不清楚),您需要定义 收到鼠标事件的班级新活动。在回收后,它会引发一个新的自定义事件。另一个类被定义为(自定义事件)收到通知。

对于moe信息(这不是可以在几行中预先提供的东西) 可以在这里联系:

How to propagate an Event up to the MainForm?

如果您在谈论WPF,则会有不同的事件概念:事件路由。如果您的类是在接收实际鼠标事件的组件的UI树中存在的UI元素,那么它也将传播到您的类。所以不需要更多编码。

答案 2 :(得分:1)

为了扩大JotaBe的答案,我可以看到两种情况:

a)A类调用B类中的方法,并发生异常。在这种情况下,您不需要执行任何操作:异常将遍历堆栈,直到找到catch语句。所以,实际上,您需要做的就是不捕获异常,或者如果您确实需要捕获它(用于记录目的等),那么请重新抛出它。

b)如果你需要在一些不相关的类中触发代码,作为异常的结果,那么最好的方法是使用事件。在你的班级声明:

public class ClassA
{
    public static event EventHandler<Exception> OnException;

    public void Notify(Exception ex)
    {
        if (OnException != null)
        {
            OnException(this, ex);
        }
    }
}

然后,为了得到通知,您需要的只是

ClassA.OnException += (sender, exeption) => 
{
    ... some GetHashCode ..
};

...我猜JotaBe已经在我输入时添加了所有必要的示例代码