C# 保存动态创建的表单

C# 保存动态创建的表单,c#,winforms,dynamic,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();

各位专家早上好,

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

如果我使用以下代码:

// 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?我想保存这些文件,以便在其他项目上使用。

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

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

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

编辑:

考虑到您的评论,表单是在.exe文件中编译的,然后可以使用,保存一个文本格式的
.cs
文件,您将无法使用它,但是,您可以选择创建
Windows表单控件
,它可以编译到dll库中,您可以在其他项目中使用它

您应该尝试创建一个
Windows窗体控件库


下面是一个很好的Windows窗体控件库示例:

如果我正确理解了您的问题,我希望创建包含所需属性的模型,然后我们可以序列化并将序列化模型保存为字节数组。否,我的代码根据一些用户输入创建窗体,创建的窗体需要保存为窗体,有了designer.cs和form.cs,以后我可以在另一个项目中使用它,基本上它可以让用户了解他们希望如何查看自己的表单,当他们单击save form时,表单必须保存在文件夹中,稍后我必须抓取并将逻辑放到文件夹中it@AlfredoMatute我认为你要做的是一项相当复杂的任务。也许您应该看看FluentSharp:另一种方法是实现自定义布局引擎。格式注释的意义是什么?
//将button1的文本设置为“OK”。
很明显,即使没有这样的注释,下一行也会这样做。我实际上希望在其他项目上使用我动态创建的表单,这就是为什么我需要保存设计器和要保存表单本身的csoh,作为对象而不是其属性?是的,表单本身,我想动态创建它,在运行时编辑一些内容,然后将其保存为其他项目的某种模板。@Alfredmatute我编辑了我的答案,请看一看。