从C#中的另一个表单调用按钮 [英] Invoke button from another Form in C#

查看:75
本文介绍了从C#中的另一个表单调用按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从与创建表单不同的表单中调用按钮.我有两种形式的申请:

I'm trying to invoke button from a different Form than it was created. I have application with two forms:

  • 主要
  • 第二

第二"表单是从主"表单中调用的,其代码为:

The "Second" Form is invoked from the "Main" Form with the code:

Second run_second_form = new Second();
run_second_form.Show();

在主"表单上,我有一个按钮"Button1".是否可以从第二个"表单中调用此按钮?

On the "Main" Form I have a button "Button1". Is it possible this button to be invoked from the "Second" Form?

我可以使用以下代码从创建它的主"表单中轻松调用"Button1":

I can easily invoke "Button1" from the "Main" Form where it is created, with the code:

Button1.PerformClick();

但是我无法通过第二个"表格进行操作.我尝试过:

but I'm not able to do it from the "Second" Form. I tried with:

Main.Button1.PerformClick();

但是它显示名称"Button1"在当前上下文中不存在".

but it says "The name "Button1" does not exists in the current context".

推荐答案

因此,第一件事是,当使用设计器将控件添加到表单时,控件将添加为私有".为了使控件可以在 Main 的外部访问,您需要更改辅助功能.

So, the first thing is that controls, when added to forms using the designer, are added as "Private". For the control to be accessible outside of the the for Main you need change the accessibility.

将其从私人"更改为内部"(如果两种形式在同一程序集中,则为首选);如果不是,则将其更改为公共".

Change it from "Private" to either "Internal" (preferred if the two forms are in the same assembly) or "Public" if they are not.

然后,您应该可以访问主窗体上的 Button1 控件.

Then you should be able to access the Button1 control on main form.

唯一没有显示的是如何保留对 Main 的引用,以便能够调用 Main.Button1.PerformClick().

The only thing that you don't show is how you keep a reference to Main to be able to call Main.Button1.PerformClick().

在设计器中更改辅助功能后,这是我用来测试此代码的代码:

After changing the accessibility in the designer, here's the code I used to test this:

public partial class Second : Form
{
    public Second()
    {
        InitializeComponent();
    }

    internal Main Main { get; set; }

    private void button1_Click(object sender, EventArgs e)
    {
        if (this.Main != null)
        {
            this.Main.Button1.PerformClick();
        }
    }
}

public partial class Main : Form
{
    public Main()
    {
        InitializeComponent();
    }

    private void Main_Load(object sender, EventArgs e)
    {
        Second run_second_form = new Second();
        run_second_form.Main = this;
        run_second_form.Show();
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Clicked on Main");
    }
}

对我有用.

尽管说了这么多,我认为Ctznkane525的解决方案可能是您所需的更好的解决方案.通常最好避免像这样传递对表单的引用. Main 应该只响应来自 Second 的事件.

Having said all this though, I think Ctznkane525's solution is probably a better one for what you need. It's generally better to avoid passing references to forms around like this. Main should just respond to an event from Second.

这篇关于从C#中的另一个表单调用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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