如何在C#中制作2个表单以相同的形式显示 [英] how to make 2 forms in C# be displayed in the same form

查看:99
本文介绍了如何在C#中制作2个表单以相同的形式显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,如果我有表格A和表格B,并且我希望程序以表格A开头,那么如果用户按下按钮则转到表格B但是表格B出现在用户身上,如同相同形式的A所示即我不想显示2种不同的表格表格A和表格BI要么向用户显示表格A,要么显示表格B但未显示在一起???

My question is if i have form A and Form B and i want the program to start with form A then if the user presses a button goes to form B but form B appears to the user as shown in the same form of A ie i don't want to show 2 different forms Form A and Form B I want either form A to be shown to the user or form B to be shown but not shown together???

推荐答案

将您的表单转换为UserControls,然后在主表单中创建一个实例并显示该实例。
Convert your "forms" to UserControls and then create an instance of either one in your main form and show that instead.


假设:



1.表格A是您在Win Form申请表中的主要表格。

2.表格A将创建表格B.

3。表格A上有一个按钮,如果点击将隐藏表格A并显示表格B

4.表格B上有一个按钮,如果点击则会隐藏表格B并显示表格A.

5.隐藏的表单不应显示在TaskBar中。



表单A:
Assume:

1. Form A is your main form in a Win Form Application.
2. Form A will create Form B.
3. There's a Button on Form A that if clicked will hide Form A and show Form B
4. There's a Button on Form B that if clicked will hide Form B and show Form A.
5. The Form that is hidden should not show in the TaskBar.

Form A:
public partial class FormA : Form
{
    public FormA()
    {
        InitializeComponent();
    }

    FormB B = new FormB();
 
    // Form A Load EventHandler   
    private void Form1_Load(object sender, EventArgs e)
    {
        this.ShowInTaskbar = true;

        // subscribe to the Click Event of Form B's button
        B.FormBBtn.Click += btnShowA_Click;
    }

    // the Click EventHandler for the Button on FormB
    private void btnShowB_Click(object sender, EventArgs e)
    {
        this.ShowInTaskbar = false;
        this.Hide();

        B.ShowInTaskbar = true;
        B.Show();
    }

    // the Click EventHandler for the Button on FormA
    private void btnShowA_Click(object sender, EventArgs e)
    {
        B.ShowInTaskbar = false;
        B.Hide();

        this.ShowInTaskbar = true;
        this.Show();
    }
}

表格B:

public partial class FormB : Form
{
    public FormB()
    {
        InitializeComponent();

        // set the reference to Form B's Button
        FormBBtn = btnShowA;
    }

    // expose Form B's Button via a Public Property
    public Button FormBBtn { get; private set; }
}

请注意,我们必须在表单B的构造函数中设置对表单B的Button的引用,因为表单A的实例需要访问之前的 / i>将触发表格B的加载事件以订阅表格B'按钮点击事件。

Note that we must set the reference to Form B's Button in Form B's Constructor because the instance of Form A needs access to it before the Load Event for Form B will be triggered in order to subscribe to Form B' Button Click Event.


这篇关于如何在C#中制作2个表单以相同的形式显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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