您的位置:首页 > 其它

智能设备项目: 手工添加所需控件的简单示例

2007-02-09 20:09 239 查看
以向Form中添加Menu为例 说明如何手工向窗体添加控件
(一般情况下还是在设计视图中拉取相关控件比较好
除非有的时候 用鼠标操作窗体不太方便 如操作Menu
在添加新项时 鼠标操作就感觉不是太方便
只是提供一种思路 一般不提倡这种做法)

先对智能设备项目中的窗体的文件组成做一个描述:
新建一个窗体时 有如下三个文件组成
Form1.cs 窗体类 可以设计视图和 代码两种方式查看和编辑
Form1.Designer.cs 由系统自动生成 一般情况下 我们不需要修改
Form1.resx 相关资源 XML描述

我们如果要添加这个Menu
需要修改到Form1.Designer.cs 和 Form1.cs
其中Form1.Designer.cs用于相关声明和加载
Form1.cs用于相关事件方法的编写

具体步骤如下:
1.新建智能设备项目 其自动包含窗体Form1
2.查看并编辑Form1.Designer.cs
声明MainMenu以及MenuItem 的相关属性及事件
具体编辑如下:

/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.SuspendLayout();

//
// mainMenu1
//
this.mainMenu1.MenuItems.Add(this.menuItem1);
this.mainMenu1.MenuItems.Add(this.menuItem2);
//
// menuItem1
//
this.menuItem1.Text = "新建";
this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
//
// menuItem2
//
this.menuItem2.Text = "编辑";
this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.AutoScroll = true;
this.ClientSize = new System.Drawing.Size(240, 268);
this.KeyPreview = true;
this.Menu = this.mainMenu1;
this.Name = "Form1";
this.Text = "Form1";
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;

3.查看并编辑Form1.cs
编写menuItem1和menuItem2的Click事件
具体代码如下:

//新增
private void menuItem1_Click(object sender, EventArgs e)
{
MessageBox.Show("新增");
}
//编辑
private void menuItem2_Click(object sender, EventArgs e)
{
MessageBox.Show("编辑");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐