技术开发 频道

C#深入浅出全接触:实战篇

  添加控件

  要向一个表单中添加控件或者子窗口,需要打开工具箱ToolBox。这个工具箱的概念来自VB。点击菜单“视图->工具箱”,激活工具箱功能:

  ToolBox(工具箱)窗口的样子如下图所示。现在就可以添加控件了,添加方法与Visual Studio 的以前版本一样,拖放或者双击控件都可以。

  首先在表单上托放下一个按钮和一个编辑框,然后让我们看看系统向初始组件(InitializeComponent)中增加了什么东西。

  接着在属性窗口中设置控件的属性,这与VB 中的操作方式一样。在控件上点击右键,并点中“属性”菜单条就可以调出属性窗口。

  现在看看InitializeComponent 方法,就会发现这些代码已经增加到其中了。接着手工修改一下这些代码:

this.components = new System.ComponentModel.Container ();
this.button1 = new System.WinForms.Button ();
this.textBox1 = new System.WinForms.TextBox ();
[url
=]//@this.TrayHeight[/url] = 0;
[url=]//@this.TrayLargeIcon[/url] = false;
[url=]//@this.TrayAutoArrange[/url] = true;
button1.Location = new System.Drawing.Point (16, 24);
button1.Size
= new System.Drawing.Size (88, 32);
button1.TabIndex
= 0;
button1.Text
= "Browse";
button1.Click
+= new System.EventHandler (this.button1_Click);
textBox1.Location
= new System.Drawing.Point (128, 32);
textBox1.Text
= "textBox1";
textBox1.TabIndex
= 1;
textBox1.Size
= new System.Drawing.Size (144, 20);
this.Text = "Form1";
this.AutoScaleBaseSize = new System.Drawing.Size (5, 13);
this.Click += new System.EventHandler (this.Form1_Click);
this.Controls.Add (this.textBox1);
this.Controls.Add (this.button1);

  添加事件处理器

  最后,要为按钮增加一个事件处理器,实现浏览文件的目的。在按钮上双击,打开Button1_Click事件处理器。同理,使用同样的方法可以为任何控件编写事件处理器。

protected void button1_Click (object sender, System.EventArgs e)
{
OpenFileDialog fdlg
= new OpenFileDialog();
fdlg.Title
= "C# Corner Open File Dialog" ;
fdlg.InitialDirectory
= @"c:\" ;
fdlg.Filter
= "All files (*.*)|*.*|All files (*.*)|*.*" ;
fdlg.FilterIndex
= 2 ;
fdlg.RestoreDirectory
= true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text
= fdlg.FileName ;
}
}

  到此就完成了所有步骤,剩下的就是运行这个程序。它实现了浏览一个文件,然后将选择的文件名装进文本框的功能。请下载相关代码:winFormApp.zip 。

0
相关文章