【问题标题】:How to detect call to methods from another form?如何检测从另一种形式调用方法?
【发布时间】:2012-02-22 08:37:56
【问题描述】:

我有一个名为 myForm 的 winform 应用程序。在这个表单中,我打开另一个表单:

    private OtherForm otherForm; //this is a field

    private OpenOtherForm()
    {
       if (otherForm == null)
       {
          otherForm = new OtherForm();
          otherForm.FormClosing += delegate { MessageBox.Show("OtherForm will be closed"); otherForm = null};
       }

       MessageBox.Show("Form is already active!");
    }

这很好用。但我也有第二种形式的一些方法。我想尝试捕捉他们的电话。

例如,如果在第二个表单中调用 OtherForm.DoSomething(),我想要一个消息框来显示。

我尝试分配OtherForm.DoSomething() += delegate { /* mesagebox */}; 但这不能编译

【问题讨论】:

  • 编译时收到的错误信息是什么??
  • 您确实将 DoSomething 声明为事件,对吧?事件也没有括号,这可能是原因。请改用OtherForm.DoSomething += delegate { };
  • 不,DoSomething 只是一个返回字符串的普通方法。

标签: c# winforms events delegates


【解决方案1】:

otherForm.FormClosing += delegate { .. } 正在编译,因为 FormClosing 是 Event 类型。可以订阅一个事件,当它被触发时,您的代码就会运行。

您不能在DoSomething() 之类的方法上使用此语法。只能使用otherForm.DoSomething() 之类的方式调用方法。然后会执行DoSomething() 中的代码。

您可以做的是创建自己的事件并在 DoSomething() 以第二种形式执行时触发它。

Here is the MSDN Documentation 发布您自己的活动。

应该是这样的:

public event EventHandler RaiseCustomEvent;

public void DoSomething()
{
    OnRaiseCustomEvent();
}

protected virtual void OnRaiseCustomEvent()
{
    EventHandler handler = RaiseCustomEvent;

    if (handler != null)
    {
         handler(this, EventArgs.Empty););
    }
}

【讨论】:

    【解决方案2】:

    如果您想以另一种形式响应调用,您可以将事件添加到另一种形式并在您尝试响应的方法中引发它。

    class Form1: Form
    {
        public void Button1_Click(object sender, EventArgs e)
        {
            var form2 = new Form2();
            form2.SomeMethodCalled += Form2_SomeMethodCalled;
        }
    
        public void Form2_SomeMethodCalled(object sender, EventArgs e)
        {
            // method in form2 called
        }
    }
    
    
    class Form2 : Form
    {
        public event EventHandler SomeMethodCalled;
    
        public void SomeMethod()
        {
            OnSomeMethodCalled();
            // .....
        }
    
        private void OnSomeMethodCalled()
        {
            var s = SomeMethodCalled;
            if(s != null)
            {
                s(this, EventArgs.Empty);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 2012-03-22
      • 2013-05-08
      • 2017-09-28
      相关资源
      最近更新 更多