本文介绍了窗口表单之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在用两个窗口窗体-MainForm和NextForm构建一个项目.
在MainForm中,我有一个方法可以根据NextForm的响应来做一件事或另一件事;

Hi,
I m building a project with two window forms - MainForm and NextForm.
In MainForm I have a method which depending on the response from NextForm will do either one thing or the other;

public void performAction()
{
if(response == true)
{
//do something
}
//the rest of the code
}


我需要从NextForm获取布尔响应.

NextForm包含:


I need to get the boolean response from NextForm.

NextForm contains:

public delegate void Confirmation(bool answer);
public event Confirmation sendConfirmation;

private void button1_Click(object sender, EventArgs e)
{
    this.sendConfirmation(true);
    this.Dispose();
}


private void button2_Click(object sender, EventArgs e)
{
    this.sendConfirmation(false);
    this.Dispose();
}


如何在MainForm中获得响应而又没有为此创建额外的方法?

我将有20种方法会请求NextForm的响应,因此可能会提供很多额外的代码,这些代码我想避免...


how can I get a response in MainForm without creating an extra method for that?

I will have like 20 methods which will ask for response from NextForm, so that might give a lot of extra code which I would like to avoid...

推荐答案

public enum ActionType { button1, button2 /* ...*/ };
public delegate void Confirmation(bool answer, ActionType actionType);
public event Confirmation sendConfirmation;
private void button1_Click(object sender, EventArgs e)
{
    this.sendConfirmation(true, ActionType.button1);
    this.Dispose();
}

private void button2_Click(object sender, EventArgs e)
{
    this.sendConfirmation(false, ActionType.button2);
    this.Dispose();
}



主要形式



in main form

public void performAction(NextForm.ActionType actionType)
{
   switch(actionType) {
     case NextForm.ActionType.<pre>

Button1;
休息;
案例NextForm.ActionType.Button2;
休息;
}
}


同样在NextForm中,您可以将每个按钮上的标签设置为枚举,例如

Button1;
break;
case NextForm.ActionType.Button2;
break;
}
}


Also in NextForm you could set the tag on each button to the enum e.g.

button1.Tag = ActionType.button1;
button2.Tag = ActionType.button2;



然后有一个处理程序



then have one handler

private void any_button_Click(object sender, EventArgs e)
{
    this.sendConfirmation(true, (ActionType)(sender as Button).Tag);
}



这篇关于窗口表单之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 00:00