﻿Imports System.Runtime.InteropServices
Imports System.Windows.Forms
Imports System.Drawing

Friend Class OFDForm
    Inherits Form
    Friend FileName As String
    Friend Result As DialogResult
    Private _Owner As OpenFileDialogEx
    Private view As OpenFileDialogEx.Views
    Private once As Boolean

    'Establish communication with the owner (component) and make this form invisible:
    Public Sub New(ByVal owner As OpenFileDialogEx)
        _Owner = owner
        view = _Owner.DefaultView
        Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        Me.Opacity = 0
        Me.ShowInTaskbar = False
        Me.Size = New Size(1, 1)
    End Sub

    'Show the Windows Forms OpenFileDialog and collect the result:
    Protected Overrides Sub OnShown(ByVal e As System.EventArgs)
        once = False
        Using ofd As New OpenFileDialog
            ofd.Filter = _Owner.Filter
            ofd.FilterIndex = _Owner.FilterIndex
            ofd.InitialDirectory = _Owner.InitialDirectory
            ofd.Title = _Owner.Title
            Me.Result = ofd.ShowDialog
            Me.FileName = ofd.FileName
        End Using
        Me.Close()
    End Sub

#Region "WndProc and Interop"
    Private Const WM_ENTERIDLE = &H121
    Private Const WM_COMMAND As Integer = &H111

    'Set the default view when the ENTERIDLE message is detected:
    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If Not once AndAlso m.Msg = WM_ENTERIDLE Then
            Dim dialogHandle As New IntPtr(m.LParam.ToInt32)
            Dim listViewHandle As IntPtr = _
                    (FindWindowEx(dialogHandle, _
                                  IntPtr.Zero, _
                                  "SHELLDLL_DefView", String.Empty))
            SendMessage(listViewHandle, WM_COMMAND, _
                                  CType(view, IntPtr), IntPtr.Zero)
            once = True
        End If
        MyBase.WndProc(m)
    End Sub

    'Interop functions:
    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Private Shared Function SendMessage(ByVal hWnd As IntPtr, _
                                            ByVal Msg As UInteger, _
                                            ByVal wParam As IntPtr, _
                                            ByVal lParam As IntPtr) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Private Shared Function FindWindowEx(ByVal parentHandle As IntPtr, _
                                             ByVal childAfter As IntPtr, _
                                             ByVal lclassName As String, _
                                             ByVal windowTitle As String) As IntPtr
    End Function
#End Region

End Class
