【问题标题】:Mouse Event from one class, how do I listen for it in another class?一个班级的鼠标事件,我如何在另一个班级收听它?
【发布时间】:2012-05-07 17:29:16
【问题描述】:

我在表单上有一个用户控件, 当我在那个用户控件上鼠标移动时,我想在表单中做一些事情。

如何让表单“监听”此事件?

我正在使用 Visual C#、.Net framework 3.5、winforms

【问题讨论】:

  • 您必须提供更多信息。你是winforms还是asp.net?这是按钮点击事件还是其他?
  • 请不要将事件表述为异常处理的术语“抛出”和“捕获”,否则会引起各种混乱。

标签: c#


【解决方案1】:

我想您指的是使用控件或类似的东西。

您可以添加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;
        }

    }

【讨论】:

    【解决方案2】:

    如果您在谈论Windows Forms(从问题中不清楚),您需要定义 接收鼠标事件的类中的新事件。接收后会引发一个新的自定义事件。另一个类订阅了那个(自定义事件)接收通知。

    关于教育部信息(不是几行就可以呈现的) 可以看这里:

    How to propagate an Event up to the MainForm?

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

    【讨论】:

      【解决方案3】:

      为了扩展 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 在我输入时已经添加了所有必要的示例代码

      【讨论】:

        猜你喜欢
        • 2018-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-05
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        相关资源
        最近更新 更多