窗口表单之间的通信 [英] communication between window forms

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

问题描述


我正在用两个窗口窗体-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...

推荐答案

为什么不是我们的枚举?例如

Why not us an enum? e.g.

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);
}


如果将mainform声明为nextform的所有者,则可以在mainform中包含公共变量,并在nextform中为其分配值.
或者,您可以使用表单的DialogResult属性.
you can have public variables in mainform and assign values to these in nextform, if you state mainform as the owner of the nextform.
alternatively you can use the DialogResult property of forms.


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆