8. 在上述组件拖入窗体后,分别按照表07所示设定各组件的属性:
| 组件类型 |
组件名称 |
属性 |
设置结果 |
| Form |
Form1 |
Text |
全面掌握对话框 |
| MaximizeBox |
False |
| FormBorderStyle |
FixedSingle |
| Button |
Button1 |
Text |
打开 |
| FlatStyle |
Flat |
| Button |
Button2 |
Text |
保存 |
| Button2 |
FlatStyle |
Flat |
| Button |
Button3 |
Text |
字体 |
| FlatStyle |
Flat |
| Button |
Button4 |
Text |
颜色 |
| FlatStyle |
Flat | 表07:【全面掌握对话框】项目中各组件主要属性值
并按照图04所示排列窗体中的各组件:
 图04:【全面掌握对话框】项目中各组件的排列顺序
9. 把Visual Studio .Net的当前窗口切换到Form1.vb的代码编辑窗口,并在Form1.vb文件的头部添加下列代码,下列代码是导入Form1.vb中使用的类所在的命名空间:
10. 在Form1.vb文件中的InitializeComponent过程之后添加下列代码,下列代码是在Form1.vb中定义Button1-Button4组件的Click事件:
Private Sub Button1_Click ( ByVal sender As System.Object , ByVal e As System.EventArgs ) Handles Button1.Click Dim strFileName As String ' 设定打开文件对话框的属性 With OpenFileDialog1 .Filter = "Text files ( *.txt )|*.txt" .InitialDirectory = "C:" .Title = "打开文件对话框" End With '以下是打开文本文件,并通过文本框显示出来 If OpenFileDialog1.ShowDialog ( ) = DialogResult.OK Then strFileName = OpenFileDialog1.FileName Dim objReader As StreamReader = New StreamReader ( strFileName , System.Text.Encoding.Default ) TextBox1.Text = objReader.ReadToEnd ( ) objReader.Close ( ) objReader = Nothing End If End Sub
Private Sub Button2_Click ( ByVal sender As System.Object , ByVal e As System.EventArgs ) Handles Button2.Click Dim strFileName As String '设定文件保存对话框的属性 With SaveFileDialog1 .DefaultExt = "txt" .FileName = strFileName .Filter = "Text files ( *.txt )|*.txt" .FilterIndex = 1 .InitialDirectory = "C:\" .OverwritePrompt = True .Title = "文件保存对话框" End With '以下是把文本框中的文字另保存为文本文件 If SaveFileDialog1.ShowDialog ( ) = DialogResult.OK Then strFileName = SaveFileDialog1.FileName Dim objWriter As StreamWriter =New StreamWriter ( strFileName , False , System.Text.Encoding.Default ) objWriter.Write ( TextBox1.Text ) objWriter.Close ( ) objWriter = Nothing End If End Sub
Private Sub Button3_Click ( ByVal sender As System.Object , ByVal e As System.EventArgs ) Handles Button3.Click ' 设定字体对话框的属性 FontDialog1.ShowColor = True '显示字体对话框,并判断十分单击对话框中的"确定"按钮 If FontDialog1.ShowDialog ( ) = DialogResult.OK Then TextBox1.Font = FontDialog1.Font '设定文本框的字体 TextBox1.ForeColor = FontDialog1.Color '设定文本框的前景色 End If End Sub
Private Sub Button4_Click ( ByVal sender As System.Object , ByVal e As System.EventArgs ) Handles Button4.Click If ColorDialog1.ShowDialog ( ) = DialogResult.OK Then TextBox1.BackColor = ColorDialog1.Color '设定文本框的背景色 End If End Sub | 11. 在上述步骤都正确完成后,【全面掌握对话框】项目的全部工作就完成了。此时单击快捷键F5就可以运行程序,图05是【全面掌握对话框】运行界面:
 图05:【全面掌握对话框】的运行界面
图06程序在是使用文件保存对话框保存文本框中数据时的界面:
 图06:【全面掌握对话框】使用文件保存对话框来保存文件
八.总结:
上面已经介绍了在VB.NET中定制Windows系统的六种常见对话框的具体实现方法。由于篇幅所限,还有一些设定对话框属性没有具体的介绍,其实掌握这些属性是非常容易的,只需耽误您一点时间,在上述代码中添加一些代码就可以。相信您一定能够完成这些工作,其实编程水平的不断提高,最重要的一点就是多试验。我们下一节再见!
|
|