保存动态创建的表单

时间:2018-10-22 20:08:48

标签: c# winforms dynamic

早上好专家

我正在尝试将动态表单保存到文件中,表单没有与保存相关的属性。

如果我使用以下代码:

// Create a new instance of the form.
            Form form1 = new Form();
            // Create two buttons to use as the accept and cancel buttons.
            Button button1 = new Button();
            Button button2 = new Button();

            // Set the text of button1 to "OK".
            button1.Text = "OK";
            // Set the position of the button on the form.
            button1.Location = new Point(10, 10);
            // Set the text of button2 to "Cancel".
            button2.Text = "Cancel";
            // Set the position of the button based on the location of button1.
            button2.Location
               = new Point(button1.Left, button1.Height + button1.Top + 10);
            // Set the caption bar text of the form.   
            form1.Text = "My Dialog Box";
            // Display a help button on the form.
            form1.HelpButton = true;

            // Define the border style of the form to a dialog box.
            form1.FormBorderStyle = FormBorderStyle.FixedDialog;
            // Set the MaximizeBox to false to remove the maximize box.
            form1.MaximizeBox = false;
            // Set the MinimizeBox to false to remove the minimize box.
            form1.MinimizeBox = false;
            // Set the accept button of the form to button1.
            form1.AcceptButton = button1;
            // Set the cancel button of the form to button2.
            form1.CancelButton = button2;
            // Set the start position of the form to the center of the screen.
            form1.StartPosition = FormStartPosition.CenterScreen;

            // Add button1 to the form.
            form1.Controls.Add(button1);
            // Add button2 to the form.
            form1.Controls.Add(button2);

如何将其保存到form1.cs和form1.designer.cs?我想保存这些文件,以便可以在其他项目中使用它们。

1 个答案:

答案 0 :(得分:1)

使用已提供的应用程序设置:

Properties.Settings.Default.FormText = "Some Value"; //this is a string value, for checkboxes it can be boolean , ...
Properties.Settings.Default.Save(); 

您可以找到more info about it in here

您可能还希望将设置以某种自定义格式或只是序列化的json格式保存到文本文件中,但是我建议您使用第一个选项。

编辑:

考虑到您的评论,将窗体编译为.exe文件,然后可以使用它,将其保存为文本格式的.cs文件,但是您将无法使用它,但是创建Windows Form Control的选项,则可以将其编译为dll库,供您在其他项目中使用。

您应该尝试创建Windows Form Control Library

这是Windows窗体控件库的一个很好的示例:https://www.mindstick.com/Articles/51/creating-and-using-windows-forms-control-library-in-c-sharp-dot-net