050使用文件对话框
程序员文章站
2022-07-03 21:44:24
...
1.添加方本框
2.添加菜单
名称为mainMenu。为菜单添加一个文件菜单项,其中包含子菜单项’“新建",“打开…”。 “保存”和“另存为…”。
3.新建事件
Private filename As String = "未命名文档"
Private Sub NewMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewMenuItem.Click
filename = "未命名文档"
txtBoxEdit.Clear()
End Sub
4.向窗体添加OpenFileDialog控件,将其Name属性修改为OpenFileDlg,Filter属性设置为下列字符串,并将Fiiterlndex的属性设置为2,使所有文件成为默认选项。
文本文件(*.txt)|*.txt|所有文件(*.*)|*.*
5.为“打开”菜单项添加事件处理程序,以显示“打开”对话框,读取选中的文件。
Private filename As String = "未命名文档"
Private Sub OpenMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenMenuItem.Click
If OpenFileDlg.ShowDialog = Windows.Forms.DialogResult.OK Then
filename = OpenFileDlg.FileName
OpenFile()
End If
End Sub
Private Sub OpenFile()
Try
txtBoxEdit.Clear()
txtBoxEdit.Text = IO.File.ReadAllText(filename)
Catch ex As Exception
MessageBox.Show(ex.Message, "文本编辑器", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
6.添加SaveFileDialog,设计Filter属性,名称改为SaveFileDlg
文本文件(*.txt)|*.txt|所有文件(*.*)|*.*
7.为保存为添加事件
Private Sub SaveAsMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsMenuItem.Click
If SaveFileDlg.ShowDialog = DialogResult.OK Then
filename = SaveFileDlg.FileName
SaveFile()
End If
End Sub
Private Sub SaveFile()
Try
IO.File.WriteAllText(filename, txtBoxEdit.Text)
Catch ex As Exception
MessageBox.Show(ex.Message, "文本编辑器", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
8.为保存添加事件
Private Sub SaveMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveMenuItem.Click
If filename = "未命名文档" Then
SaveAsMenuItem.PerformClick()
Else
SaveFile()
End If
End Sub