(1)实例化一个控件;
(2)设置控件实例属性;
(3)将控件实例添加到窗体的Controls集合中
【示例】用代码向窗体添加一个命令按钮,单击这个按钮关闭窗口并退出
(1)在Visual Studio中新建一个“Windos 窗体应用程序”
(2)窗体代码Form1.cs如下:
using System
using System.Collections.Generic
using System.Windows.Forms
using System.Drawing
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent()
//实例化一个命令按钮
Button btn = new Button()
//设置命令按钮的属性
btn.Location = new Point(50, 50)
btn.Size = new Size(80, 25)
btn.Text = "退出"
btn.Click += btn_Click
//添加到窗口的Controls集合中
this.Controls.Add(btn)
}
void btn_Click(object sender, EventArgs e)
{
this.Close()
}
}
}
(3)运行效果
窗体启动后
点击“退出”按钮后,窗口关闭。
教你一个方法你先在界面上拖一个pannel控件
比如:pannel1
然后,打开窗体代码页,搜索 pannel1
这样你可以看见,系统是怎么创建这个pannel1的,它只不过自动生成了代码而已。
所有的控件都可以用这个方法。
具体代码:
this.mypan = new myPanel()
this.SuspendLayout()
//
// panel1
//
this.mypan.Dock = System.Windows.Forms.DockStyle.Fill//这个是pannel充满窗体,你可以修改其他的
this.mypan.Location = new System.Drawing.Point(0, 0)
this.mypan.Name = "mypan"
this.mypan.Size = new System.Drawing.Size(632, 402)
this.mypan.TabIndex = 0
this.Controls.Add(this.mypan)
this.ResumeLayout(false)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)