Create an image viewer application in Visual Basic 6 and VB.NET
This program enables users to search for image files on their computer and view them in a picture box. We'll explore two implementation methods for VB6 and their equivalent in VB.NET.
Use DriveListBox, DirListBox and FileListBox to create a file browser interface
Simpler method using CommonDialog control to open image files
Modern implementation using OpenFileDialog and PictureBox
This method uses DriveListBox, DirListBox, and FileListBox controls to create a file browser interface. It requires more setup but provides a fully integrated browsing experience.
Private Sub Combo1_Change()
'To list all graphics files or all files
If ListIndex = 0 Then
File1.Pattern = ("*.bmp;*.wmf;*.jpg;*.gif")
Else
File1.Pattern = ("*.*")
End If
End Sub
Private Sub Dir1_Change()
'Update file list when directory changes
File1.Path = Dir1.Path
File1.Pattern = ("*.bmp;*.wmf;*.jpg;*.gif")
End Sub
Private Sub Drive1_Change()
'Update directory when drive changes
Dir1.Path = Drive1.Drive
End Sub
Private Sub File1_Click()
'Handle file selection
If Combo1.ListIndex = 0 Then
File1.Pattern = ("*.bmp;*.wmf;*.jpg;*.gif")
Else
File1.Pattern = ("*.*")
End If
If Right(File1.Path, 1) <> "\" Then
filenam = File1.Path + "\" + File1.FileName
Else
filenam = File1.Path + File1.FileName
End If
End Sub
Private Sub show_Click()
'Display selected image
If Right(File1.Path, 1) <> "\" Then
filenam = File1.Path + "\" + File1.FileName
Else
filenam = File1.Path + File1.FileName
End If
Picture1.Picture = LoadPicture(filenam)
End Sub
In VB.NET, we use the OpenFileDialog control to select images and the PictureBox control to display them.
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
'Configure OpenFileDialog
With OpenFileDialog1
.Title = "Select Image File"
.Filter = "Image Files|*.bmp;*.jpg;*.jpeg;*.gif;*.png;" & _
"*.tif;*.tiff;*.ico|All Files|*.*"
.Multiselect = False
End With
'Show dialog and handle selection
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Try
'Load the selected image
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
'Update status
lblStatus.Text = Path.GetFileName(OpenFileDialog1.FileName)
lblSize.Text = $"Size: {New FileInfo(OpenFileDialog1.FileName).Length / 1024:n0} KB"
Catch ex As Exception
MessageBox.Show("Error loading image: " & ex.Message,
"Image Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
End Try
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Set initial PictureBox properties
PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
PictureBox1.BorderStyle = BorderStyle.Fixed3D
End Sub
Try the Picture Viewer functionality right in your browser. Select an image from the file browser to view it.
Comprehensive guide covering VB6 and VB.NET with practical examples.
View on Amazon