Page 1 of 1

Using The WebBrowser Control As A Document Viewer Rate Topic: -----

#1 ricardosms  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 73
  • View blog
  • Posts: 301
  • Joined: 02-April 10

Posted 02 December 2011 - 05:47 AM

Using Webbrowser Control To View Documents

Hello:

The WebBrowser control that comes with the NET framework allows you to have a quick viewer for documents. Maybe the terminology wouldn't be to open a file to view, but to navigate to a file. Well, it won't allow to have too much control over the way the document is displayed, but it is easy to use.

The WebBrowser control is just the Internet Explorer on a cut down, smaller version. So you will need to create the toolbars and navigation buttons, but this is not what I intend to show you here.

You could view images, webpages, text documents, and if your regular browser has the activex for pdf documents installed, you could view them too, without opening a new window.


Attached Image


This small program has a split container, a webbrowser control, a treeview, a listview, a combobox, two buttons, a menu strip, an imagelist and a folderbrowserdialog.

When you start the program there is a treeview with two nodes, set for your documents folder and to your pictures folder. Those are the most likely places to contain what you would like to view.

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TreeView1.Sort()
        Me.AllowDrop = True  'This will let you drag and drop files to your browser
        Dim trNode As New TreeNode

        trNode.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)
        trNode.Tag = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)
        trNode.Nodes.Add("*DUMMY*") 'They can be expanded again after collapsing
        TreeView1.Nodes.Add(trNode)

        Dim trNode1 As New TreeNode
        trNode1.Text = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
        trNode1.Tag = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
        trNode1.Nodes.Add("*DUMMY*")
        TreeView1.Nodes.Add(trNode1)
        ListView1.View = View.Details
        ListView1.Columns.Add("File Name", 150, HorizontalAlignment.Left)
        ComboBox1.Items.Add("Images")
        ComboBox1.Items.Add("Html")
        ComboBox1.Items.Add("PDF")
        ComboBox1.Items.Add("Text")
        ComboBox1.Items.Add("All Files")
        ComboBox1.SelectedIndex = 0

    End Sub



The default documents to view are the images, determined by the combobox items list. The listview will show the images in your MyDocuments folders if there is any. You could click on any of them and the webbrowser will show the image. You could, instead click the pictures folder on the treview and it will show the list of the images on MyPictures folder, or you could expand the nodes to view inside subfolders.

If you want to view another folder on you computer, you could call from the menu a folderbrowser dialog that will allow you to open another folder on a different place in your computer.

The listview will also show the icons matching yor filetype. Those icons are loaded to an imagelist through calls to an API using the next structure and code:

Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Windows.Forms

Public Class DocumentViewer
    Private TheLongPath As String = ""
    Private filType As Integer = 0

  Private Structure SHFILEINFO
        Public hIcon As IntPtr       
        Public iIcon As Integer          
        Public dwAttributes As Integer   
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
        Public szDisplayName As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> _
        Public szTypeName As String
    End Structure
    Private Declare Auto Function SHGetFileInfo Lib "shell32.dll" _
               (ByVal pszPath As String, _
                ByVal dwFileAttributes As Integer, _
                ByRef psfi As SHFILEINFO, _
                ByVal cbFileInfo As Integer, _
                ByVal uFlags As Integer) As IntPtr

    Private Const SHGFI_ICON = &H100
    Private Const SHGFI_SMALLICON = &H1
    Private Const SHGFI_LARGEICON = &H0    ' Large icon
    Private Const MAX_PATH = 260



    Private Sub AddImages(ByVal strFileName As String)

        Dim shInfo As SHFILEINFO
        shInfo = New SHFILEINFO()
        shInfo.szDisplayName = New String(vbNullChar, MAX_PATH)
        shInfo.szTypeName = New String(vbNullChar, 80)
        Dim hIcon As IntPtr
        hIcon = SHGetFileInfo(strFileName, 0, shInfo, Marshal.SizeOf(shInfo), SHGFI_ICON Or SHGFI_SMALLICON)
        Dim MyIcon As Drawing.Bitmap
        MyIcon = Drawing.Icon.FromHandle(shInfo.hIcon).ToBitmap
        ImageList1.Images.Add(strFileName.ToString(), MyIcon)

    End Sub



The node expanding and collapsing routines will clear the treeview and listview contents and gather new information every time you click on a node and will display it on a new view.

    Private Sub TreeView1_BeforeCollapse(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeCollapse

        e.Node.Nodes.Clear()        ' Empty To Avoid Double Entries
        e.Node.Nodes.Add("*DUMMY*") 'To be able to expand again
    End Sub




    Private Sub TreeView1_BeforeExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeExpand

        e.Node.Nodes.Clear()        ' Empty it To Avoid Double Entries
        Dim dirNode As IO.DirectoryInfo ' get the directory for this node
        dirNode = New IO.DirectoryInfo(e.Node.Tag.ToString)

        ' addsubdirectories to each node
        For Each subDir As IO.DirectoryInfo In dirNode.GetDirectories
            If (subDir.Attributes And FileAttributes.Hidden) <> FileAttributes.Hidden Then

                Dim subDirNode As New TreeNode ' Create a child TreeNode for the next subdirectory

                subDirNode.Tag = subDir.FullName ' Save Full path to this directory
                subDirNode.Text = subDir.Name ' Set display text
                subDirNode.Nodes.Add("*DUMMY*")
                e.Node.Nodes.Add(subDirNode) ' add child TreeNode to the expanding TreeNode
            End If
        Next
    End Sub




    Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
        Dim folder As String = CStr(TreeView1.SelectedNode.Tag)
        Dim FileTypes0 As String = ".gif.bmp.jpg.tif.png"
        Dim FileTypes1 As String = ".htm.mht.asp"
        Dim FileTypes2 As String = ".pdf"
        Dim FileTypes3 As String = ".txt.asc"
        Dim FileTypes4 As String = "*.*"
        Dim ending As String

        ListView1.Items.Clear()
        If Not folder Is Nothing AndAlso IO.Directory.Exists(folder) Then
            TheLongPath = folder
            Try
                For Each file As String In IO.Directory.GetFiles(folder)
                    ending = file.Substring(file.LastIndexOf("."c)).ToLower 'Detect filetype against list
                    AddImages(file)
                    Select Case filType
                        Case 0
                            If InStr(FileTypes0, ending) Then ListView1.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())
                        Case 1
                            If InStr(FileTypes1, ending) Then ListView1.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())
                        Case 2
                            If InStr(FileTypes2, ending) Then ListView1.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())
                        Case 3
                            If InStr(FileTypes3, ending) Then ListView1.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())
                        Case 4
                            ListView1.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())

                    End Select
                Next
            Catch ex As Exception
                ' MessageBox.Show(ex.Message)
            End Try

        End If

        ListView1.Refresh()

    End Sub




When you expand a node, the subfolders will be shown, and they can be expanded too. Depending on your file type selection on the combobox, the listview will show the corresponding files in the folder by calling a recursive routine AddAllFolders:

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        filType = ComboBox1.SelectedIndex
        TreeView1.Focus()
    End Sub



Here we will weed out hidden files, that can give you errors on trying to access:

    Private Sub AddAllFolders(ByVal TNode As TreeNode, ByVal FolderPath As String)
        Try
            For Each FolderNode As String In Directory.GetDirectories(FolderPath)
                Dim FolderInfo As New DirectoryInfo(FolderNode)

                ' Prevents Errors for Hidden Folders
                If (FolderInfo.Attributes And FileAttributes.Hidden) <> FileAttributes.Hidden Then
                    Dim SubFolderNode As TreeNode = TNode.Nodes.Add(FolderNode.Substring(FolderNode.LastIndexOf("\"c) + 1))
                    SubFolderNode.Tag = FolderNode
                    SubFolderNode.Nodes.Add("*DUMMY*")
                End If

            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub



If you click on any item shown on the listview, the webbrowser will navigate there. You could then use the arrow up or down to view other files or click on any particular one you want to view:

    Private Sub ListView1_ItemSelectionchanged(ByVal sender As Object, ByVal e As System.Windows.Forms.ListViewItemSelectionchangedEventArgs) Handles ListView1.ItemSelectionchanged
        Dim lCount As Integer

        For lCount = 0 To ListView1.Items.Count - 1
            If ListView1.Items(lCount).Selected = True Then
                ListView1.EnsureVisible(lCount) ' Selection Is At View
                If filType > 3 Then GoTo skip
                WebBrowser1.Navigate(TheLongPath & "\"c & ListView1.Items(lCount).SubItems(0).Text)
                Exit For
            End If
        Next
skip:
    End Sub



When you want to change folder from your menu, you start everything again. A folderbrowser dialog appears for you to select.

    Private Sub ChangeFolderToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChangeFolderToolStripMenuItem.Click
        TreeView1.Nodes.Clear()
        Try
            If fbDialog.ShowDialog = Windows.Forms.DialogResult.OK Then

                Dim trNode As New TreeNode

                '       trNode.Text = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
                trNode.Text = fbDialog.SelectedPath
                '      trNode.Tag = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
                trNode.Tag = fbDialog.SelectedPath
                trNode.Nodes.Add("*DUMMY*")
                TreeView1.Nodes.Add(trNode)

                AddAllFolders(trNode, fbDialog.SelectedPath)
                TreeView1.Refresh()
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

        Dim folder As String = fbDialog.SelectedPath
        Dim FileTypes0 As String = ".gif.bmp.jpg.tif.png"
        Dim FileTypes1 As String = ".htm.mht.asp"
        Dim FileTypes2 As String = ".pdf"
        Dim FileTypes3 As String = ".txt.asc"
        Dim FileTypes4 As String = "*.*"
        Dim ending As String

        ListView1.Items.Clear()

        If Not folder Is Nothing AndAlso IO.Directory.Exists(folder) Then
            TheLongPath = folder
            Try
                For Each file As String In IO.Directory.GetFiles(folder)
                    ending = file.Substring(file.LastIndexOf("."c)).ToLower 'Detect filetype against list
                    AddImages(file)
                    Select Case filType
                        Case 0
                            If InStr(FileTypes0, ending) Then ListView1.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())
                        Case 1
                            If InStr(FileTypes1, ending) Then ListView1.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())
                        Case 2
                            If InStr(FileTypes2, ending) Then ListView1.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())
                        Case 3
                            If InStr(FileTypes3, ending) Then ListView1.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())
                        Case 4
                            ListView1.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1), file.ToString())

                    End Select
                Next
            Catch ex As Exception
                MessageBox.Show(ex.Tostring)
            End Try

        End If

        ListView1.Refresh()

    End Sub



You could also navigate back and forth by clicking the butons "Forward" and "Back". They will command the web browser to go back to the documents already viewed, on both directions.

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        WebBrowser1.GoBack()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        WebBrowser1.GoForward()
    End Sub



The webbrowser will automaticly display the scrollbars necessary to view the document. So I think it is an good way of taking advantage of a webbrowser control that is already there. You don't need to navigate out of your computer, but you could too. If any html document is viewed and it contain links. you will be navigating the internet from this program. Or you could create a navigation bar to be able to do it from there instead of opening a document containing links.

You can as you do with the regular explorer drag and drop files from a folder to the control and right click to view a menu.

Take a look to the program and if you desire so, comment please.

Thank you.

Attached File(s)



Is This A Good Question/Topic? 4
  • +

Replies To: Using The WebBrowser Control As A Document Viewer

#2 DimitriV  Icon User is offline

  • They don't think it be like it is, but it do
  • member icon

Reputation: 584
  • View blog
  • Posts: 2,738
  • Joined: 24-July 11

Posted 07 December 2011 - 10:48 PM

Pretty good... Pretty good...
However, I would suggest adding a path bar and displaying the path by using <webbrowser>.Url.AbsolutePath
Happy coding!
Was This Post Helpful? 0
  • +
  • -

#3 trevster344  Icon User is offline

  • The Peasant
  • member icon

Reputation: 224
  • View blog
  • Posts: 1,505
  • Joined: 16-March 11

Posted 12 December 2011 - 04:24 PM

Well done. All comes down to what YOU want to do with your application.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1