1

我想创建一个基于单个模板表单的 32 个 Windows 表单,并且这些实例应该相互链接。也就是说,每个 Form 都有一个用于调用下一个实例的按钮,依此类推。我可以创建任意数量的表单,但是如何将这些实例链接在一起?

这是我用来创建几个子表单的:

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

    private void button1_Click(object sender, EventArgs e)
    {
        ChildForm child = new ChildForm();
        child.Show();
    }
}

事件顺序如下:

  • 用户启动应用程序,显示主窗体(只有“打开子”按钮)
  • 用户按下“打开子”按钮,子表单的第一个实例打开
  • 第一个子表单(标题“子表单 1”)有按钮“打开子表单 2”
  • 如果用户按下“打开子表单 2”,子表单 1 被隐藏,子表单 2 被显示
  • 如果到达最后一个子表单,则环绕到子表单 1

欢迎任何想法!

问候

克里斯

4

2 回答 2

1

您可以创建表单的静态集合,在构造函数中将表单实例添加到列表中(并在处置期间将其删除)。要找出下一个表单,您可以找到当前表单的索引并根据该索引在列表中获取下一个表单。创建一个带有两个按钮的表单,并按如下方式对其进行修改以进行测试。

 public partial class Form1 : Form
    {
        static List<Form1> formList = new List<Form1>();
        public Form1()
        {
            InitializeComponent();
            formList.Add(this);
        }



        private void button1_Click(object sender, EventArgs e)
        {
            int idx = formList.IndexOf(this);
            int nextIdx = (idx == formList.Count()-1 ?  0: idx+1 );

            Form1 nextForm = formList[nextIdx];
            nextForm.changeTextAndFocus("next form: " + nextIdx);
        }

        // moves to the next form and changes the text
        public void changeTextAndFocus(string txt)
        {
            this.Focus();
            this.Text = txt;
        }

        //Creates 5 forms
        private void button2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 5; i++)
            {
                Form1 newForm = new Form1();
                newForm.Show();
            }
        }
    }
于 2013-02-24T22:25:02.197 回答
0

我真的不知道你打算做什么:)。如果要计算多个表单,可以在表单中添加属性 Number。并从那里向上搜索。

主窗体;

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

     private void button1_Click(object sender, EventArgs e)
     {
         ChildForm first = new ChildForm();
         first.Number = 1;
         first.Show();
     }
}

子窗体

public partial class ChildForm : Form
{
    public ChildForm()
    {
        // createButton here
    }
    private void button_Click(object sender, EventArgs e)
    {
        ChildForm _childForm = new ChildForm();
        _childForm.Owner = this;
        _childForm.Number = this.Number + 1;
        this.Hide();
        _childForm.Show();
    }

    public void FirstChildForm()
    {
        if (this.Number != 1) //maybe not that static
        {
            (this.Owner as ChildForm).FirstChildForm();
            this.Close(); // or hide or whatever
        }
    }
    public int Number
    { get; set; }
}

未经测试的代码,希望这会有所帮助:)。

于 2013-02-24T22:17:36.667 回答