Creating a new instance of form1 and change that forms property

橙三吉。 提交于 2019-12-25 11:58:16

问题


In my current project, I am making a sticky-note type application in which the user can have multiple instances open of the same form. However, I was wondering if there was a way in C# where I can create a new instance of form1 however have the new form's title/text/heading to be form2.

If this is achievable, I would like a nudge into the correct direction of how to code that part of my app.

Thanks everyone.

--EDIT--

I realized I forgot to add something important:

I need to be able to calculate how many instances are currently open. From there I will add +1 to the form text.


回答1:


Try accessing the forms properties from the class:

MyForm newForm = new MyForm();
newForm.Show();
newForm.Text = "Form2";

Or call a method from the current form to set the text:

// In MyForm
public void SetTitle(string text)
{
    this.Text = text;
}

// Call the Method
MyForm newForm = new MyForm();
newForm.Show();
newForm.SetTitle("Form2");

Hope this helps!

To check the amount of forms open you could try something like this:

// In MyForm
private int counter = 1;
public void Counter(int count)
{
    counter = count;
}
// Example
MyForm newForm = new MyForm();
counter++;
newForm.Counter(counter);

It may be confusing to use, but lets say you have a button that opens a new instance of the same form. Since you have one form open at the start counter = 1. Every time you click on the button, it will send counter++ or 2 to the form. If you open another form, it will send counter = 3 and so on. There might be a better way to do this but I am not sure.




回答2:


Use a static field to keep a count of how many instances have been opened, and use it to set the form's caption.

Here's a sketch; if you want different behavior you could skip the OnFormClosed override:

public class TheFormClass : Form
{
    private static int _openCount = 0;

    protected override void OnLoad(EventArgs e)
    {
        _openCount++;
        base.OnLoad(e);
        this.Text = "Form" + _openCount;
    }

    protected override void OnFormClosed(FormClosedEventArgs e)
    {
        _openCount--;
        base.OnFormClosed(e);
    }
}


来源:https://stackoverflow.com/questions/11573562/creating-a-new-instance-of-form1-and-change-that-forms-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!