简体   繁体   English

从C#中的隐藏形式调用控件

[英]Calling controls from a hidden form in C#

I am designing a Windows form application wherein I need to call, from Form A, a click event for a command button on Form B. Form B needs to remain hidden at all times. 我正在设计Windows窗体应用程序,其中需要从窗体A调用窗体B上命令按钮的click事件。窗体B需要始终保持隐藏状态。 It was simple to do this in Visual Basic, I'd just call it like this: "FormName.ControlName.Event/Method". 在Visual Basic中这样做很简单,我只是这样称呼它:“ FormName.ControlName.Event / Method”。

This isn't working for me now in C#, Visual Studio 8. Can anyone help? 现在在C#,Visual Studio 8中这对我不起作用。有人可以帮忙吗?

All you need to do is give Form A a reference to Form B. Presumably there is some startup code in your application that is aware of both forms. 您需要做的就是为Form A提供对Form B的引用。大概您的应用程序中有一些启动代码可以识别这两种形式。 If so, you could have code like this: 如果是这样,您可能会具有以下代码:

// starting up
FormB b = new FormB();
b.Visible = false;

FormA a = new FormA();
a.FormBInstance = b; // you would have to add the 'FormBInstance' property to Form A class yourself
a.Show();

// Now, if Form A needs to do something with FormB, it just needs to use the FormBInstance property.

Make sense? 说得通?

You can't raise events from a different class directly, they have special access level that means you can only subscribe/unsubscribe. 您不能直接从其他类引发事件,它们具有特殊的访问级别,这意味着您只能订阅/取消订阅。 You would need method on formB that can raise the event. 您可能需要在formB上引发事件的方法。

听起来很古怪,但是引用了Form B的实例,并公开了Button控件:

b.myButton.PerformClick();

You should create a public method on FormB that does what you need. 您应该在FormB上创建一个可以满足您需要的公共方法。 This way, you get rid of the need to directly call the click event handler, which is not a great thing to do. 这样,您就无需直接调用click事件处理程序,这不是一件好事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM