C# 窗体生成器

<!-- [if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning /> <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas /> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:SpaceForUL /> <w:BalanceSingleByteDoubleByteWidth /> <w:DoNotLeaveBackslashAlone /> <w:ULTrailSpace /> <w:DoNotExpandShiftReturn /> <w:AdjustLineHeightInTable /> <w:BreakWrappedTables /> <w:SnapToGridInCell /> <w:WrapTextWithPunct /> <w:UseAsianBreakRules /> <w:DontGrowAutofit /> <w:UseFELayout /> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!-- [if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--><!-- [if gte mso 10]> <mce:style><! /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} table.MsoTableGrid {mso-style-name:网格型; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; border:solid windowtext 1.0pt; mso-border-alt:solid windowtext .5pt; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-border-insideh:.5pt solid windowtext; mso-border-insidev:.5pt solid windowtext; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} --><!-- [endif]-->

要测试 C#windowns 应用程序,当其 Form 很多时, exe 文件运行效率会不会变慢,机器内存会不会暴涨?为此,需要新建很多个 Form 。一种方法则是通过 vs2005 ide 不断地新建 Form 修改其 NameText ,另外则可以以某个 Form 作为模板,通过设置产生个数、新窗体的命名规则等自动产生 Forms ,然后将这些 Forms 加入到工程中编译即可,本文即阐述了如何自动产生窗体。

通常 C# 的一个 Form 其有 3 个文件组成: *.cs, *.Designer.cs, *.resx ,其中 .cs 文件为核心代码文件,而 Designer.cs 文件则为窗体的设计文件, .resx 为资源文件。架设我们以 Form1 作为模板产生新的窗体,则只需修改 Form1.cs 文件中的 class Form1class 目标名称, *.Designer.csclass Form1class 目标名称, *.Designer.csthis.name=this.name= 新名称 ;//*.Designer.csthis.text=this.text=text;// ,同时复制资源文件即可。

新建一窗体,取名为 FrmGenerate ,然后注意下述的核心组件:

<!-- [if !supportLists]-->1) <!-- [endif]-->ButtonsimpleButton1设置保存路径;

<!-- [if !supportLists]-->2) <!-- [endif]-->ButtonsimpleButton2 ,生成窗体;

<!-- [if !supportLists]-->3) <!-- [endif]-->ButtonsimpleButton3 , 选择窗体模板;

...

public partial class FrmGenerate : DevExpress.XtraEditors.XtraForm

{

public FrmGenerate()

{

InitializeComponent();

}

// 加载窗体模板

private String loadFormCodes(String fileName)

{

//

String content = "" ;

try

{

using (StreamReader st = new StreamReader (fileName, System.Text.Encoding .GetEncoding("GBK" )))

{

content = st.ReadToEnd();

st.Close();

}

}

catch (Exception exp)

{

MessageBox .Show(exp.Message);

}

return content;

}

// 设置保存路径

private void simpleButton1_Click(object sender, EventArgs e)

{

using (FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog ())

{

if (folderBrowserDialog1.ShowDialog() == DialogResult .OK)

{

this .txtSaveDic.Text = folderBrowserDialog1.SelectedPath;

}

}

}

// 生成窗体

private void generateForm(String frmBase, int index, String frmName, String frmTitle)

{

// 替换class 名称

String cs = this .memoCS.Text.Replace(frmBase, frmName);

String designerCs = this .memoDesigner.Text.Replace(frmBase, frmName);

String csFileName = Path .Combine(this .txtSaveDic.Text, frmName + ".cs" );

String designerFileName = Path .Combine(this .txtSaveDic.Text, frmName + ".Designer.cs" );

// 替换nametext 属性

designerCs = designerCs.Replace("this.Name" , "this.Name = \"" + frmName + "\";//" ); //this.Name = "FrmGrid";

designerCs = designerCs.Replace("this.Text" , "this.Text = \"" + frmTitle + "\";//" );//this.Text = " 表格演示...";

//

writeFile(cs, csFileName);

writeFile(designerCs, designerFileName);

try

{

File .Copy(this .txtFormName.Text + ".resx" , Path .Combine(this .txtSaveDic.Text, frmName + ".resx" ));

}

catch (Exception exp)

{

}

}

// 保存cs,resx 文件

private void writeFile(String context, String fileName)

{

try

{

FileStream fs = new FileStream (fileName, FileMode .Create);

// 获得字节数组

byte [] data = System.Text.Encoding .GetEncoding("GBK" ).GetBytes(context);

// 开始写入

fs.Write(data, 0, data.Length);

// 清空缓冲区、关闭流

fs.Flush();

fs.Close();

}

catch (Exception exp)

{

}

}

// 生成窗体

private void simpleButton2_Click(object sender, EventArgs e)

{

if (this .txtClassName.Text.Trim().Length < 1)

{

MessageBox .Show(" 请输入ClassName!" );

return ;

}

if (this .txtSaveDic.Text.Trim().Length < 1)

{

MessageBox .Show(" 请选择保存路径!" );

return ;

}

if (this .txtFormTitle.Text.Trim().Length < 1)

{

MessageBox .Show(" 请设置窗体标题!" );

return ;

}

if (this .txtFormNameAs.Text.Trim().Length < 1)

{

MessageBox .Show(" 请设置窗体Name!" );

return ;

}

if (this .spinEdit2.Value < this .spinEdit1.Value)

{

MessageBox .Show(" 窗体数设置有误!" );

return ;

}

if (this .txtFormName.Text.LastIndexOf("\\" ) < 0)

{

MessageBox .Show(" 请选择窗体模板!" );

return ;

}

//

String frmBase = this .txtFormName.Text.Substring(this .txtFormName.Text.LastIndexOf("\\" ) + 1);

// frmBase.

for (int i = (int )this .spinEdit1.Value; i < (int )this .spinEdit2.Value; i++)

{

generateForm(this .txtClassName.Text, i, this .txtFormNameAs.Text + i.ToString(), this .txtFormTitle.Text + i.ToString());

}

MessageBox .Show(" 窗体生成成功! 详见目录:" + this .txtSaveDic.Text);

}

// 选择窗体模板

private void simpleButton3_Click(object sender, EventArgs e)

{

using (OpenFileDialog dialog = new OpenFileDialog ())

{

dialog.Filter = "C# 代码文件和资源文件(*.cs,*.resx)|*.cs;*.resx" ;

if (dialog.ShowDialog() == DialogResult .OK)

{

//

String fileName = dialog.FileName;

if (!String .IsNullOrEmpty(fileName))

{

fileName = fileName.ToLower();

if (fileName.EndsWith("Designer.cs" ))

{

MessageBox .Show(" 请选择Form 窗体的核心类文件,Form1.cs" );

return ;

}

fileName = fileName.Substring(0, fileName.LastIndexOf("." ));

this .txtFormName.Text = fileName;

String formName = fileName.Substring(fileName.LastIndexOf("\\" ) + 1);

//formName = formName.Substring(0, formName.LastIndexOf("."));

//

String fileCs = this .txtFormName.Text + ".cs" ;

String fileDesigner = this .txtFormName.Text + ".Designer.cs" ;

String fileResx = this .txtFormName.Text + ".resx" ;

tabCS.Text = formName + ".cs" ;

tabDesigner.Text = formName + ".Designer.cs" ;

tabResource.Text = formName + ".resx" ;

memoCS.Text = loadFormCodes(fileCs);

memoDesigner.Text = loadFormCodes(fileDesigner);

memoRes.Text = loadFormCodes(fileResx);

//

}

}

}

}

}

以下是一个简单的C#窗体随机数生成器的示例代码: ```csharp using System; using System.Windows.Forms; namespace RandomNumberGenerator { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnGenerate_Click(object sender, EventArgs e) { int length = Convert.ToInt32(txtLength.Text); bool preventDuplicate = chkPreventDuplicate.Checked; bool sleep = chkSleep.Checked; RandomNumberGenerator generator = new RandomNumberGenerator(length, preventDuplicate, sleep); string result = generator.Generate(); txtResult.Text = result; } } public class RandomNumberGenerator { private int length; private bool preventDuplicate; private bool sleep; public RandomNumberGenerator(int length, bool preventDuplicate, bool sleep) { this.length = length; this.preventDuplicate = preventDuplicate; this.sleep = sleep; } public string Generate() { string result = string.Empty; Random random = new Random(); while (result.Length < length) { int randomNumber = random.Next(0, 36); char character = GetCharacter(randomNumber); if (!preventDuplicate || !result.Contains(character.ToString())) { result += character.ToString(); } if (sleep) { System.Threading.Thread.Sleep(1); } } return result; } private char GetCharacter(int randomNumber) { if (randomNumber < 10) { return (char)('0' + randomNumber); } else { return (char)('a' + randomNumber - 10); } } } } ``` 在窗体中,用户可以指定所需的随机数长度、是否防止重复以及是否需要线程休眠。生成随机数的方法是在RandomNumberGenerator类中实现的,该方法使用Random类生成随机数,并使用GetCharacter方法将数字转换为字母数字字符。如果用户选择了防止重复选项,则在生成随机数时检查结果中是否已经包含了当前字符。如果用户选择了线程休眠选项,则在生成每个字符之间暂停1毫秒。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值