Create a program that will allow the user to browse and select a pdf file then open the selected file using visual basic 6.
To solve the problem above we are going to create a step by step tutorial that will teach us how to browse pdf files in our computer, get the path and open it using Visual Basic 6.
Follow the simple steps:
- Open your visual basic 6 program then select Standard EXE.
- A new project will be created with a Form1 on it.
- We need to add the following control to our form:
- 1 label
- 1 textbox
- 2 command buttons
- 1 common dialog
Note: name the textbox into txtpath. Leave the rest of the control to its default name.
- Common dialog control is not loaded in the basic component of vb6, we need to add it in the components menu. In the menu bar select Project then Components. A dialog box will appear, in the control tab scroll down, find and check the Microsoft Common Dialog Control 6.0 (SP6). Click OK.
- The design of the form should look like the image below.
- Next is we’re going to add a Module. Project in the menu bar then select Add Module.
- Paste the code below to the newly created module.
Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
- Back to the form. Double click the browse button and paste the code
With CommonDialog1 .DialogTitle = "Browse PDF" .Filter = "PDF Files(*.pdf)|*.pdf" .ShowOpen txtpath.Text = (CommonDialog1.FileName) End With
The code will allow you to browse pdf files only and display the path of the file in a textbox.
- Double click Open PDF button and paste the code
Dim strFile As String If txtpath.Text = "" Then MsgBox "Please select a pdf file." Else strFile = txtpath.Text ShellExecute 0&, "open", strFile, "", "", MAXIMIZE End If
The code will open the pdf file using the path of the selected file.
- Save the project and Run it (press F5)