在没有ShowDialog()的Windows窗体之间传递变量

When you are programming a Windows Forms application, you will invariably need to get variables from a second form window, such as an options form or popup search prompt.

在编写Windows Forms应用程序时,总是需要从第二个窗体窗口获取变量,例如选项窗体或弹出搜索提示。

Most of the guides out there will tell you that you have to open the second form with ShowDialog(), which blocks the user from doing anything else until they’ve closed the second form window. This won’t work very well for a find/replace dialog, for instance. It also won’t work very well for custom drawn popup forms.

那里的大多数指南都会告诉您,您必须使用ShowDialog()打开第二个窗体,这将阻止用户执行其他操作,直到他们关闭了第二个窗体窗口。 例如,这对于查找/替换对话框将无法很好地工作。 对于自定义绘制的弹出表单,它也不能很好地工作。

The quick way to pass variables between the forms is using Delegates. You can set an eventhandler for the Closing event of the second form, and handle the event in the first form. This allows you to capture variables before the second form window has closed.

在表单之间传递变量的快速方法是使用委托。 您可以为第二个表单的Closing事件设置一个事件处理程序,并在第一个表单中处理该事件。 这样,您可以在第二个窗体窗口关闭之前捕获变量。

For this exercise, we’re going to assume that we have two forms:

对于本练习,我们将假设我们有两种形式:

MainForm

主窗体

OptionsForm

选项表格

We’re going to further assume that we’ve clicked some sort of button that opens the OptionsForm with a Show() method call. Now let’s take a look at the magic:

我们将进一步假设我们单击了某种按钮,该按钮通过Show()方法调用打开OptionsForm。 现在让我们看一下魔术:

……. snip…….

……。 剪……。

OptionsForm theform = new OptionsForm();theform.Closing += new CancelEventHandler(theform_Closing);theform.Show();

OptionsForm theform =新的OptionsForm(); theform.Closing + =新的CancelEventHandler(theform_Closing); theform.Show();

}

}

private void theform_Closing(object sender, CancelEventArgs e){

私人无效theform_Closing(对象发送者,CancelEventArgs e){

   OptionsForm theform = (OptionsForm)sender;

OptionsForm theform =(OptionsForm)sender;

   // Grab the variable from the options form. The options form should set this variable before it closes, and the variable should be marked as public.   string localvar = theform.thestringvariable;

//从选项表单中获取变量。 选项表单应在关闭该变量之前对其进行设置,并且该变量应标记为public。 字符串localvar = theform.thestringvariable;

}

}

That’s all there is to it.

这里的所有都是它的。

翻译自: https://www.howtogeek.com/howto/programming/pass-variables-between-form-windows-without-showdialog/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值