help:关于C#中的事件 [英] help :about event in c#

查看:94
本文介绍了help:关于C#中的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在学习c#,并且了解许多面向对象的思想.
根据C#中的事件",我认为这是非常有用的.我的问题是:
如果我的项目中有一个主窗体和另一个子窗体,而该子窗体为
通过构造子窗体对象并调用showdialog方法在mainform中激活.同时在子窗体中有一个按钮,当用户单击此按钮时,我们可以在.net创建的button_click事件处理程序功能中执行某些操作.
如何通知主表单该子表单正在处理button_click事件,并将焦点设置在主表单上.
谢谢.

i am studying c# recently and understand many object-oriented ideas.
acording to "event" in c# ,i think it is very useful. my question is:
if there is a main form and another subform in my project and the subform is
actived in mainform by constructing a subform object and calling showdialog method. at the same time there is a button in subform, when user click this button ,we can do something in button_click event handler funtion created by .net .
how can i inform the main form that the subform is now dealing with button_click event and set the focus on main form.
thanks.

推荐答案

以这种方式更改焦点不是一个好主意,但是您可以对事件进行以下操作:

1)通过将修改器设置为public并将其附加到主窗体中来公开子窗体上的按钮.

2)创建一个新事件,并在子窗体中将其触发,然后像以前一样在主窗体中附加到它.
Changing focus this way is a bad idea, but you can do the following for the events :

1) Expose the button on the subform by setting the modifier to public and attaching on to it in the main form.

2) Creating a new event and firing that in the sub form, and attaching on to it in the main form as before.


因为您正在使用ShowDialog函数显示第二个窗体,如果不关闭新对话框,将无法将焦点返回到主窗体.首先要做的是使用Show而不是ShowDialog打开第二个表单.
然后,您可以用第二种形式定义一个事件.可以这样简单:
Because you are using the ShowDialog function to show your 2nd form, you won''t be able to return focus to your main form without closing the new dialog. The first thing to do is to open your 2nd form using Show and not ShowDialog.
Then you can define an event in your second form. It can be as simple as this:
public delegate void NoArgsEvent();
public event NoArgsEvent OnButtonClickEventNotify;


要引发事件,只需在form2上的按钮单击处理程序中添加一个简单的小代码块即可.


To cause the event to fire, just add a simple little block of code into your button click handler on form2.

if( OnButtonClickEventNotify != null )
{
    OnButtonClickEventNotify();
}



然后在您的主表单中,您只需要在创建第二个表单的实例时使用该事件即可:



Then in your main form you just have to consume the event when you create an instance of your 2nd form:

var dlg = new form2();
form2.OnButtonClickEventNotify += YourHandler;

void YourHandler()
{
    // Do something useful here.
    focus(); // To set the focus back to the main form.
}


没有"subform",句点之类的概念.请询问有效的内容.

—SA
There is no such concept as "subform", period. Please ask about something valid.

—SA


这篇关于help:关于C#中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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