Embedding source code in a source program


 






















  1. Option Strict On
  2. Imports System.ComponentModel
  3. Imports System.Runtime.InteropServices
  4. Imports System.Text
  5. Imports Shell32
  6. Public Class Form1
  7.     Dim Shell_Application As Shell32.Shell
  8.     Dim SelectedPath As String
  9.     Dim DateTimeFormat As String
  10.     Dim Time_Interval As TimeSpan
  11.     Dim MyTaskFactory As TaskFactory
  12.     Dim IsBusyFindingFiles As Boolean
  13.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  14.         Dim RectangleConverter As New RectangleConverter()
  15.         Dim a As Rectangle =
  16.               CType(RectangleConverter.ConvertFromString(My.Settings.Form1Position), Rectangle)

  17.         Tracer.Append($"{Me.StartPosition} {Me.WindowState}
  18.        {Me.Location} {Me.Size}
  19.        {a.Location} {a.Size}")

  20.         Me.Location = a.Location
  21.         Me.Size = a.Size
  22.         Me.WindowState = CType(
  23.               Int32.Parse(My.Settings.WindowState), FormWindowState)

  24.         hWnd_Form1 = Me.Handle
  25.         CheckBox1.Checked = Bool_Find_Filename
  26.         CheckBox2.Checked = Bool_Modified_Files
  27.         CheckBox3.Checked = Bool_Like_Filename
  28.         TextBox1.Text = FileNameToBeFound
  29.         TextBox2.Text = Like_FileNameToBeFound
  30.         Label2.Text = SelectedPath
  31.         Me.Button1.Focus()
  32.     End Sub
  33.     Sub Initialize()
  34.         Try
  35.             Me.Button1.Text = My.Settings1.Default.Button1Text
  36.             Me.Button2.Text = My.Settings1.Default.Button2Text
  37.             Me.CheckBox1.Text = My.Settings1.Default.CheckBox1Text
  38.             Me.CheckBox2.Text = My.Settings1.Default.CheckBox2Text
  39.             Me.CheckBox3.Text = My.Settings1.Default.CheckBox3Text
  40.             Me.DateTimeFormat = My.Settings1.Default.DateTimeFormat
  41.             Me.Text = My.Settings1.Default.Form1Text
  42.             SelectedPath = My.Settings.SelectedPath
  43.             Like_FileNameToBeFound = My.Settings.Like_FilenameToBeFound
  44.             FileNameToBeFound = My.Settings.FilenameToBeFound
  45.             Dim BoolConverter As New BooleanConverter()
  46.             Bool_Find_Filename = CType(BoolConverter.ConvertFromString(
  47.                My.Settings.Bool_Find_Filename), Boolean)
  48.             Bool_Like_Filename = CType(BoolConverter.ConvertFromString(
  49.                My.Settings.Bool_Like_Filename), Boolean)
  50.             Bool_Modified_Files = CType(BoolConverter.ConvertFromString(
  51.                My.Settings.Bool_Modified_Files), Boolean)
  52.         Catch ex As Exception

  53.         End Try
  54.         Dim Time_Now As DateTime = DateTime.Now
  55.         Time_UpLimitation = Time_Now.AddMinutes(-1)
  56.         Time_DownLimitation = Time_Now
  57.         With DateTimePicker1
  58.             .Format = DateTimePickerFormat.Custom
  59.             .CustomFormat = DateTimeFormat
  60.             .Value = DateTime.Parse(Time_UpLimitation.ToString(DateTimeFormat))
  61.         End With
  62.         With DateTimePicker2
  63.             .Format = DateTimePickerFormat.Custom
  64.             .CustomFormat = DateTimeFormat
  65.             .Value = DateTime.Parse(Time_DownLimitation.ToString(DateTimeFormat))
  66.         End With
  67.         Set_Time_Interval()
  68.     End Sub
  69.     Private Sub Form1_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
  70.         Dim RectangleConverter As New RectangleConverter()
  71.         Dim WindowState2 As FormWindowState = Me.WindowState
  72.         Dim Rectange2 As New Rectangle(Me.Location, Me.Size)
  73.         If Me.WindowState <> FormWindowState.Normal Then
  74.             WindowState2 = PreviousWindowState
  75.             Rectange2 = Me.RestoreBounds
  76.         End If
  77.         My.Settings.WindowState = CInt(WindowState2).ToString()
  78.         My.Settings.Form1Position = RectangleConverter.ConvertToString(Rectange2)

  79.         My.Settings.SelectedPath = SelectedPath
  80.         My.Settings.Like_FilenameToBeFound = Like_FileNameToBeFound
  81.         My.Settings.FilenameToBeFound = FileNameToBeFound

  82.         Dim BoolConverter As New BooleanConverter()
  83.         My.Settings.Bool_Find_Filename = BoolConverter.ConvertToString(Bool_Find_Filename)
  84.         My.Settings.Bool_Like_Filename = BoolConverter.ConvertToString(Bool_Like_Filename)
  85.         My.Settings.Bool_Modified_Files = BoolConverter.ConvertToString(Bool_Modified_Files)

  86.     End Sub
  87.     Dim PreviousWindowState As FormWindowState
  88.     Protected Overrides Sub WndProc(ByRef m As Message)
  89.         Static BackColor_Button1 As Color = Me.Button1.BackColor
  90.         Select Case m.Msg
  91.             Case WM_MyMessage
  92.                 If m.WParam = IntPtr.Zero Then
  93.                     Me.IsBusyFindingFiles = False
  94.                     Me.Button1.BackColor = BackColor_Button1
  95.                 ElseIf m.WParam = New IntPtr(1) Then
  96.                     Me.Button1.BackColor = Color.DarkGreen
  97.                 Else
  98.                     MsgBox($"{m.WParam.ToInt32}", Title:="WM_MyMessage")
  99.                 End If
  100.                 m.Result = IntPtr.Zero
  101.                 Exit Sub
  102.             Case WM_SIZE
  103.                 If m.WParam.ToInt32 = SIZE_MAXIMIZED Then
  104.                     PreviousWindowState = FormWindowState.Maximized
  105.                 ElseIf m.WParam.ToInt32 = SIZE_RESTORED Then
  106.                     PreviousWindowState = FormWindowState.Normal
  107.                 End If
  108.         End Select
  109.         MyBase.WndProc(m)
  110.     End Sub
  111.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  112.         Static FirstTime As Boolean = True
  113.         If IsBusyFindingFiles Then Exit Sub
  114.         If FirstTime Then
  115.             FirstTime = False
  116.             Shell_Application = New Shell32.Shell()
  117.             MyTaskFactory = New TaskFactory(
  118.                     TaskCreationOptions.PreferFairness Or
  119.                     TaskCreationOptions.LongRunning, Nothing)
  120.         End If
  121.         Dim SelectedFolder As Folder = CType(Shell_Application.NameSpace(SelectedPath), Folder)
  122.         Dim FindFiles As New Find_Files_Class
  123.         Button1.BackColor = Color.Red
  124.         MyTaskFactory.StartNew(AddressOf FindFiles.FindFiles_and_ShowResult, SelectedFolder)
  125.     End Sub
  126.     Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) _
  127.         Handles DateTimePicker1.ValueChanged, DateTimePicker2.ValueChanged
  128.         Time_UpLimitation = DateTimePicker1.Value
  129.         Time_DownLimitation = DateTimePicker2.Value
  130.         Set_Time_Interval()
  131.     End Sub
  132.     Sub Set_Time_Interval()
  133.         Static BackColor_Label1 As Color = Label1.BackColor
  134.         Time_Interval = DateTimePicker2.Value - DateTimePicker1.Value
  135.         Label1.Text = $"{Time_Interval,18:c}"
  136.         Label1.BackColor = If(Time_Interval <= TimeSpan.Zero, Color.Red, BackColor_Label1)
  137.     End Sub
  138.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
  139.         Static FirstTime_Folder As Boolean = True
  140.         If FirstTime_Folder Then
  141.             FirstTime_Folder = False
  142.             FolderBrowserDialog1.SelectedPath = SelectedPath
  143.             FolderBrowserDialog1.ShowNewFolderButton = False
  144.         End If
  145.         If DialogResult.OK = FolderBrowserDialog1.ShowDialog(New HWND_IWin32(Me.Handle)) Then
  146.             SelectedPath = FolderBrowserDialog1.SelectedPath
  147.             Label2.Text = SelectedPath
  148.         End If
  149.         Button1.Focus()
  150.     End Sub
  151.     Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
  152.         Bool_Find_Filename = CheckBox1.Checked
  153.     End Sub
  154.     Private Sub CheckBox2_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox2.CheckedChanged
  155.         Bool_Modified_Files = CheckBox2.Checked
  156.     End Sub
  157.     Private Sub CheckBox3_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox3.CheckedChanged
  158.         Bool_Like_Filename = CheckBox3.Checked
  159.     End Sub
  160.     Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
  161.         FileNameToBeFound = TextBox1.Text
  162.     End Sub
  163.     Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
  164.         Like_FileNameToBeFound = TextBox2.Text
  165.     End Sub
  166.     Dim Tracer As New StringBuilder
  167.     Private Sub Form1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles Me.MouseDoubleClick
  168.         MsgBox(Tracer.ToString())
  169.     End Sub

  170.     Private Sub Form1_Layout(sender As Object, e As LayoutEventArgs) Handles Me.Layout
  171.         Static FirstTime As Boolean = True
  172.         If FirstTime Then
  173.             FirstTime = False
  174.             Me.Initialize()
  175.         End If
  176.     End Sub
  177. End Class

  178. Module Module1
  179.     Public Null As IntPtr = IntPtr.Zero
  180.     Public hWnd_Form1 As IntPtr
  181.     Public Time_UpLimitation As DateTime
  182.     Public Time_DownLimitation As DateTime
  183.     Public Bool_Find_Filename As Boolean
  184.     Public Bool_Like_Filename As Boolean
  185.     Public Bool_Modified_Files As Boolean
  186.     Public FileNameToBeFound As String
  187.     Public Like_FileNameToBeFound As String
  188.     Class HWND_IWin32
  189.         Implements IWin32Window
  190.         Dim _Handle As IntPtr
  191.         Sub New(hWnd As IntPtr)
  192.             _Handle = hWnd
  193.         End Sub
  194.         Public ReadOnly Property Handle As IntPtr Implements IWin32Window.Handle
  195.             Get
  196.                 Return _Handle
  197.             End Get
  198.         End Property
  199.     End Class

  200.     Function GetProcessId_from_hWnd(hWnd As IntPtr) As UInt32
  201.         Dim ProcessId As UInt32
  202.         Dim ThreadId As UInt32
  203.         If GetWindow(hWnd, GW_OWNER) = Null AndAlso IsWindowVisible(hWnd) Then
  204.             ThreadId = GetWindowThreadProcessId(hWnd, ProcessId)
  205.         End If
  206.         Return ProcessId
  207.     End Function

  208.     Public Const FORMAT_MESSAGE_FROM_SYSTEM As UInteger = &H1000
  209.     Public Const WM_MOVE As UInt32 = &H3
  210.     Public Const WM_SIZE As UInt32 = &H5
  211.     Public Const SIZE_RESTORED As Integer = 0
  212.     Public Const SIZE_MINIMIZED As Integer = 1
  213.     Public Const SIZE_MAXIMIZED As Integer = 2
  214.     Public Const SIZE_MAXSHOW As Integer = 3
  215.     Public Const SIZE_MAXHIDE As Integer = 4
  216.     Public Const WM_SETFOCUS As UInt32 = &H7
  217.     Public Const WM_KILLFOCUS As UInt32 = &H8
  218.     Public Const WM_ENABLE As UInt32 = &HA
  219.     Public Const WM_SETREDRAW As UInt32 = &HB
  220.     Public Const WM_SETTEXT As UInt32 = &HC
  221.     Public Const WM_GETTEXT As UInt32 = &HD
  222.     Public Const WM_GETTEXTLENGTH As UInt32 = &HE
  223.     Public Const WM_PAINT As UInt32 = &HF
  224.     Public Const WM_CLOSE As UInt32 = &H10
  225.     Public Const WM_QUERYOPEN As UInt32 = &H13
  226.     Public Const WM_QUIT As UInt32 = &H12
  227.     Public Const WM_COMMAND As UInt32 = &H111
  228.     Public Const WM_SYSCOMMAND As UInt32 = &H112
  229.     Public Const WM_APP As UInt32 = &H8000
  230.     Public Const WM_USER As UInt32 = &H400
  231.     Public Const WM_MyMessage As UInt32 = WM_APP
  232.     Public Const MAX_PATH As Int32 = 260

  233.     Enum Flag_BIF
  234.         BIF_RETURNONLYFSDIRS = &H1  ' For finding a folder to start document searching
  235.         BIF_DONTGOBELOWDOMAIN = &H2  ' For starting the Find Computer
  236.         BIF_STATUSTEXT = &H4      ' Top Of the dialog has 2 lines Of text For BROWSEINFO.lpszTitle And one line If
  237.         ' this flag Is set.  Passing the message BFFM_SETSTATUSTEXTA to the hwnd can set the
  238.         '  // rest of the text.  This Is Not used with BIF_USENEWUI And BROWSEINFO.lpszTitle gets
  239.         ' // all three lines of text.
  240.         BIF_RETURNFSANCESTORS = &H8
  241.         BIF_EDITBOX = &H10   '// Add an editbox To the dialog
  242.         BIF_VALIDATE = &H20   '// insist on valid result (Or CANCEL)

  243.         BIF_NEWDIALOGSTYLE = &H40   '// Use the New dialog layout with the ability to resize
  244.         '// Caller needs to call OleInitialize() before using this API

  245.         BIF_USENEWUI = (BIF_NEWDIALOGSTYLE Or BIF_EDITBOX)

  246.         BIF_BROWSEINCLUDEURLS = &H80 '// Allow URLs To be displayed Or entered. (Requires BIF_USENEWUI)
  247.         BIF_UAHINT = &H100 '// Add a UA hint To the dialog, In place Of the edit box. May Not be combined With BIF_EDITBOX
  248.         BIF_NONEWFOLDERBUTTON = &H200 '// Do Not add the "New Folder" button To the dialog.  Only applicable With BIF_NEWDIALOGSTYLE.
  249.         BIF_NOTRANSLATETARGETS = &H400 '// don 't traverse target as shortcut

  250.         BIF_BROWSEFORCOMPUTER = &H1000 '// Browsing For Computers.
  251.         BIF_BROWSEFORPRINTER = &H2000  '// Browsing For Printers
  252.         BIF_BROWSEINCLUDEFILES = &H4000 '// Browsing For Everything
  253.         BIF_SHAREABLE = &H8000  '// sharable resources displayed (remote shares, requires BIF_USENEWUI)
  254.         BIF_BROWSEFILEJUNCTIONS = &H10000 '// allow folder junctions Like zip files And libraries To be browsed
  255.     End Enum
  256.     Public GW_HWNDFIRST As UInt32 = 0
  257.     Public GW_HWNDLAST As UInt32 = 1
  258.     Public GW_HWNDNEXT As UInt32 = 2
  259.     Public GW_HWNDPREV As UInt32 = 3
  260.     Public GW_OWNER As UInt32 = 4
  261.     Public GW_CHILD As UInt32 = 5
  262.     Public GW_ENABLEDPOPUP As UInt32 = 6
  263.     Public GW_MAX As UInt32 = 6

  264.     Public Const S_OK As Int32 = 0
  265.     Public Const S_FALSE As Int32 = 1I
  266.     Public Const PMSF_NORMAL As UInt32 = 0
  267.     Public Const PMSF_MULTIPLE As UInt32 = 1
  268.     Public Const PMSF_DONT_STRIP_SPACES As UInt32 = &H10000
  269.     Declare Unicode Function PathMatchSpecEx Lib "Shlwapi.dll" Alias "PathMatchSpecExW" (
  270.                  _In_LPCWSTR_pszFile As String,
  271.                  _In_LPCWSTR_pszSpec As String,
  272.                  _In_DWORD_dwFlags As UInt32) As Int32
  273.     Declare Unicode Function PathIsDirectory Lib "Shlwapi.dll" Alias "PathIsDirectoryW" (
  274.                  _In_LPCWSTR_pszPath As String) As Boolean
  275.     Declare Unicode Function PathFileExists Lib "Shlwapi.dll" Alias "PathFileExistsW" (
  276.                  _In_PCWSTR_pszPath As String) As Boolean
  277.     Declare Unicode Function FormatMessage Lib "kernel32.dll" Alias "FormatMessageW" (
  278.                 _In_DWORD_dwFlags As UInt32,
  279.                 _In_opt_LPCVOID_lpSource As IntPtr,
  280.                 _In_DWORD_dwMessageId As UInt32,
  281.                 _In_DWORD_dwLanguageId As UInt32,
  282.                 _Out_LPWSTR_lpBuffer As IntPtr,
  283.                 _In_DWORD_nSize As UInt32,
  284.                 _In_opt_va_list_Arguments As IntPtr) As UInt32
  285.     Declare Unicode Function GetLastError Lib "kernel32.dll" () As UInt32
  286.     Declare Unicode Function GetModuleFileName Lib "Kernel32.dll" Alias "GetModuleFileNameW" (
  287.             _In_opt_hModule As IntPtr,
  288.             lpFilename As IntPtr,
  289.             nSize As UInt32) As UInt32
  290.     Declare Unicode Function GetModuleFileName Lib "Kernel32.dll" Alias "GetModuleFileNameW" (
  291.                <InAttribute> _In_opt_hModule As IntPtr,
  292.                <InAttribute, Out> lpFilename As StringBuilder,
  293.                <InAttribute> nSize As UInt32) As UInt32
  294.     Declare Unicode Function CloseHandle Lib "kernel32.dll" (
  295.                 ByVal hFile As IntPtr) As Boolean
  296.     Declare Unicode Function DestroyWindow Lib "User32.dll" (
  297.                 _In_HWND_hWnd As IntPtr) As Boolean
  298.     Declare Unicode Function CloseWindow Lib "User32" (
  299.                 _In_HWND_hWnd As IntPtr) As Boolean
  300.     Declare Unicode Function FindWindow Lib "User32.dll" Alias "FindWindowW" (
  301.              _In_opt__LPCWSTR_lpClassName As String,
  302.              _In_opt__LPCWSTR_lpWindowName As String) As IntPtr
  303.     Declare Unicode Function EnableWindow Lib "User32.dll" (
  304.                 _In_HWND_hWnd As IntPtr,
  305.                 _In_BOOL_bEnable As Boolean) As Boolean
  306.     Declare Unicode Function IsWindowEnabled Lib "User32.dll" (
  307.                 _In_HWND_hWnd As IntPtr) As Boolean
  308.     Declare Unicode Function BringWindowToTop Lib "User32.dll" (
  309.                 _In_HWND_hWnd As IntPtr) As Boolean
  310.     Declare Unicode Function GetForegroundWindow Lib "User32.dll" () As IntPtr
  311.     Declare Unicode Function SetForegroundWindow Lib "User32.dll" (
  312.                 _In_HWND_hWnd As IntPtr) As Boolean
  313.     Declare Unicode Function PostMessage Lib "user32.dll" Alias "PostMessageW" (
  314.                _In_opt_HWND_hWnd As IntPtr,
  315.                _In__UINT_Msg As UInt32,
  316.                _In_WPARAM_wParam As IntPtr,
  317.                _In_LPARAM_lParam As IntPtr) As Boolean
  318.     Declare Unicode Function SetActiveWindow Lib "User32.dll" (_In_HWND_hWnd As IntPtr) As IntPtr
  319.     Declare Unicode Function SetFocus Lib "User32.dll" (
  320.                 _In_opt_HWND_hWnd As IntPtr) As IntPtr
  321.     Declare Unicode Function GetWindow Lib "User32.dll" (
  322.                 _In_HWND_hWnd As IntPtr,
  323.                 _In_UINT_uCmd As UInt32) As IntPtr
  324.     Declare Unicode Function GetDesktopWindow Lib "User32.dll" () As IntPtr

  325.     Declare Unicode Function GetWindowThreadProcessId Lib "User32.dll" (
  326.                 _In_HWND_hWnd As IntPtr,
  327.                 _Out_opt_LPDWORD_lpdwProcessId As IntPtr) As UInt32
  328.     Declare Unicode Function GetWindowThreadProcessId Lib "User32.dll" (
  329.                 _In_HWND_hWnd As IntPtr,
  330.              <InAttribute, Out> ByRef _Out_opt_LPDWORD_lpdwProcessId As UInt32) As UInt32
  331.     Declare Unicode Function IsWindowVisible Lib "user32.dll" (
  332.                 _In_HWND_hWnd As IntPtr) As Boolean
  333.     Declare Unicode Function GetWindowText Lib "User32.dll" Alias "GetWindowTextW" (
  334.                _In_HWND_hWnd As IntPtr,
  335.                _Out_writes_nMaxCount_LPWSTR_lpString As IntPtr,
  336.                _In_int_nMaxCount As Int32) As Int32  ' _Ret_range_(0, nMaxCount)
  337.     Declare Unicode Function SendMessage Lib "user32.dll" Alias "SendMessageW" (
  338.                _In__HWND_hWnd As IntPtr,
  339.                _In__UINT_Msg As UInt32,
  340.                _Pre_maybenull__Post_valid__WPARAM_wParam As IntPtr,
  341.                _Pre_maybenull___Post_valid__LPARAM_lParam As IntPtr) As IntPtr
  342. End Module









  1. Imports Shell32
  2. Public Class Find_Files_Class
  3.     Public _Time_UpLimitation As DateTime
  4.     Public _Time_DownLimitation As DateTime
  5.     Public _Bool_Find_Filename As Boolean
  6.     Public _Bool_Like_Filename As Boolean
  7.     Public _Bool_Modified_Files As Boolean
  8.     Public _FileNameToBeFound As String
  9.     Public _Like_FileNameToBeFound As String

  10.     Public ModifiedFolderItems As System.Collections.Generic.List(Of FolderItem)
  11.     Public FoundFilenames As Collections.Generic.List(Of FolderItem)
  12.     Public Like_Filenames_BeFound As Collections.Generic.List(Of FolderItem)
  13.     Public Sub New()
  14.         _Time_UpLimitation = Time_UpLimitation
  15.         _Time_DownLimitation = Time_DownLimitation
  16.         _Bool_Find_Filename = Bool_Find_Filename
  17.         _Bool_Like_Filename = Bool_Like_Filename
  18.         _Bool_Modified_Files = Bool_Modified_Files
  19.         _FileNameToBeFound = FileNameToBeFound
  20.         _Like_FileNameToBeFound = Like_FileNameToBeFound

  21.         ModifiedFolderItems = New System.Collections.Generic.List(Of FolderItem)
  22.         FoundFilenames = New Collections.Generic.List(Of FolderItem)
  23.         Like_Filenames_BeFound = New Collections.Generic.List(Of FolderItem)
  24.     End Sub
  25.     Sub clear()
  26.         ModifiedFolderItems.Clear()
  27.         FoundFilenames.Clear()
  28.         Like_Filenames_BeFound.Clear()
  29.     End Sub
  30.     Protected Overrides Sub Finalize()
  31.         clear()
  32.     End Sub
  33.     Sub FindFiles_and_ShowResult(SelectedFolder2 As Object)
  34.         PathIsNotDirectory = New List(Of String)
  35.         PathFile_NotExists = New List(Of String)
  36.         Dim SelectedFolder As Folder = CType(SelectedFolder2, Folder)
  37.         Dim Title_SelectedFolder As String = SelectedFolder.Title
  38.         FindFiles(SelectedFolder)

  39.         PostMessage(hWnd_Form1, WM_MyMessage, New IntPtr(1), Null)

  40.         Dim Excel_Outputl As New Excel_Output_Class(Me)
  41.         If _Bool_Find_Filename Then Excel_Outputl.Show_FoundFilename(Title_SelectedFolder)
  42.         If _Bool_Like_Filename Then Excel_Outputl.Show_Like_Filename_BeFound(Title_SelectedFolder)
  43.         If _Bool_Modified_Files Then Excel_Outputl.Show_ModifyFolderItem(Title_SelectedFolder)
  44.         Excel_Outputl.Common_ShowWOrkSheet()
  45.         PostMessage(hWnd_Form1, WM_MyMessage, Null, Null)
  46.     End Sub
  47.     Dim PathIsNotDirectory As List(Of String)
  48.     Dim PathFile_NotExists As List(Of String)
  49.     Sub FindFiles(InputFolder As Folder)
  50.         For Each Folder_Item As FolderItem In InputFolder.Items
  51.             If PathFileExists(Folder_Item.Path) Then
  52.                 If Folder_Item.IsFolder Then
  53.                     If Not PathIsDirectory(Folder_Item.Path) Then
  54.                         PathIsNotDirectory.Add(Folder_Item.Path)
  55.                         Continue For
  56.                     End If
  57.                     FindFiles(DirectCast(Folder_Item.GetFolder, Folder))
  58.                 Else
  59.                     FiltersCollection(Folder_Item)
  60.                 End If
  61.             Else
  62.                 PathFile_NotExists.Add(Folder_Item.Path)
  63.             End If
  64.         Next
  65.     End Sub
  66.     Function Filter_Modified_Files(Folder_item As FolderItem) As Boolean
  67.         Return _Bool_Modified_Files AndAlso
  68.                _Time_UpLimitation < Folder_item.ModifyDate AndAlso
  69.                                     Folder_item.ModifyDate < _Time_DownLimitation
  70.     End Function
  71.     Function Filter_Find_FileName(Folder_item As FolderItem) As Boolean
  72.         Return _Bool_Find_Filename AndAlso
  73.         0 = String.Compare(IO.Path.GetFileName(Folder_item.Path), _FileNameToBeFound, ignoreCase:=True)
  74.     End Function
  75.     Function Filter_Like_FileName(Folder_item As FolderItem) As Boolean
  76.         Return _Bool_Like_Filename AndAlso
  77.          S_OK = PathMatchSpecEx(Folder_item.Path, _Like_FileNameToBeFound, PMSF_DONT_STRIP_SPACES)
  78.     End Function
  79.     Public Sub FiltersCollection(Folder_Item As FolderItem)
  80.         If Filter_Modified_Files(Folder_Item) Then ModifiedFolderItems.Add(Folder_Item)
  81.         If Filter_Find_FileName(Folder_Item) Then FoundFilenames.Add(Folder_Item)
  82.         If Filter_Like_FileName(Folder_Item) Then Like_Filenames_BeFound.Add(Folder_Item)
  83.         MyEmbedProc(Folder_Item)
  84.     End Sub
  85.     Partial Private Sub MyEmbedProc(Folder_item As FolderItem)
  86.     End Sub
  87. End Class








  1. Option Strict On
  2. Imports System.Runtime.InteropServices
  3. Imports Microsoft.Office.Interop
  4. Imports Microsoft.Office.Interop.Excel
  5. Imports Shell32

  6. Public Class Excel_Output_Class
  7.     Public Excel_Application As Excel.Application
  8.     Dim Workbook As Excel.Workbook
  9.     Dim Worksheet As Excel.Worksheet
  10.     Dim NumberOf_Added_Worksheets As Int32
  11.     Dim cell As Range
  12.     Dim Find_files As Find_Files_Class
  13.     Dim Delete_Excel_Application As Boolean

  14.     Public Sub New(Find_files As Find_Files_Class)
  15.         Me.Find_files = Find_files
  16.         Delete_Excel_Application = False
  17.         Excel_Application = CType(CreateObject("Excel.Application"), Excel.Application)
  18.         Excel_Application.DisplayAlerts = False
  19.         AddHandler Excel_Application.SheetBeforeDoubleClick, AddressOf SheetBeforeDoubleClickEventHandler
  20.         AddHandler Excel_Application.WorkbookBeforeClose, AddressOf WorkbookBeforeCloseEventHandler
  21.         Workbook = Excel_Application.Workbooks.Add()
  22.         Workbook.Windows(1).Caption = "Find files"
  23.         'Workbook.Title = "My Workbook Title"
  24.         NumberOf_Added_Worksheets = 0
  25.     End Sub

  26.     '<TypeLibType(TypeLibTypeFlags.FHidden), ComVisible(False)>
  27.     <ComVisible(False)>
  28.     Public Delegate Sub AppEvents_SheetBeforeDoubleClickEventHandler(
  29.       <InAttribute(), MarshalAs(UnmanagedType.IDispatch)> Sh As Object,
  30.       <InAttribute(), MarshalAs(UnmanagedType.Interface)> Target As Range,
  31.       <InAttribute(), Out> ByRef Cancel As Boolean)

  32.     '<TypeLibType(TypeLibTypeFlags.FHidden), ComVisible(False)>
  33.     <ComVisible(False)>
  34.     Sub SheetBeforeDoubleClickEventHandler(
  35.       <InAttribute(), MarshalAs(UnmanagedType.IDispatch)> Sh As Object,
  36.       <InAttribute(), MarshalAs(UnmanagedType.Interface)> Target As Range,
  37.       <InAttribute(), Out> ByRef Cancel As Boolean)
  38.         If Target.Column <> 6 Then Exit Sub
  39.         Dim WorkSheet As Worksheet = DirectCast(Sh, Worksheet)
  40.         Dim Directory_string As String = TryCast(Target.Value2, String)
  41.         If Not PathIsDirectory(Directory_string) Then Exit Sub
  42.         Dim Filename As String = CType(Target.Offset(0, -5).Value2, String)
  43.         Dim DirectoryInfo As New IO.DirectoryInfo(Directory_string)
  44.         If DirectoryInfo.Exists Then
  45.             Dim Explorer As String = $"{Environment.GetEnvironmentVariable("SystemRoot")}\Explorer.exe"
  46.             Process.Start(Explorer, $"/n /e,/select,{DirectoryInfo.FullName}\{Filename}")
  47.         End If
  48.         Cancel = True
  49.     End Sub

  50.     Public Sub WorkbookBeforeCloseEventHandler(
  51.         <InAttribute(), MarshalAs(UnmanagedType.Interface)> Wb As Workbook,
  52.         ByRef Cancel As Boolean)
  53.         Dim hWnd As New HWND_IWin32(New IntPtr(Excel_Application.ActiveWindow.Hwnd))
  54.         If DialogResult.Cancel = MessageBox.Show(hWnd,
  55.                 "Close workbook in Excel?", "Find files", MessageBoxButtons.OKCancel) Then
  56.             Cancel = True
  57.         Else
  58.             Delete_Excel_Application = True
  59.             Close_Excel()
  60.         End If
  61.     End Sub
  62.     Sub Close_Excel()
  63.         RemoveHandler Excel_Application.SheetBeforeDoubleClick, AddressOf SheetBeforeDoubleClickEventHandler
  64.         RemoveHandler Excel_Application.WorkbookBeforeClose, AddressOf WorkbookBeforeCloseEventHandler
  65.         Excel_Application.Quit()
  66.     End Sub
  67.     Protected Overrides Sub finalize()
  68.         If Not Delete_Excel_Application Then Close_Excel()
  69.     End Sub
  70.     Sub InitializeWorksheet(title_Worksheet As String)
  71.         If NumberOf_Added_Worksheets = 0 Then
  72.             Worksheet = CType(Workbook.Worksheets(1), Excel.Worksheet)
  73.         Else
  74.             Worksheet = CType(Workbook.Worksheets.Add(), Excel.Worksheet)
  75.         End If
  76.         NumberOf_Added_Worksheets += 1
  77.         Worksheet.Name = title_Worksheet
  78.         cell = Worksheet.Range("A2")
  79.         cell.Font.Size = 16
  80.     End Sub

  81.     Sub Common_ShowWOrkSheet()
  82.         Excel_Application.ActiveWindow.WindowState = Excel.XlWindowState.xlMaximized
  83.         Excel_Application.Visible = True
  84.         Excel_Application.ActiveWindow.Visible = True
  85.         Dim hWnd_Excel As IntPtr = New IntPtr(Excel_Application.ActiveWindow.Hwnd)
  86.         If GetForegroundWindow() <> hWnd_Excel Then
  87.             AppActivate(CInt(GetProcessId_from_hWnd(hWnd_Excel)))
  88.         End If
  89.     End Sub
  90.     Sub Show_FoundFilename(Title_SelectedFloder As String)
  91.         Dim FoundFilenames As List(Of FolderItem) = Me.Find_files.FoundFilenames
  92.         InitializeWorksheet("Find filename")
  93.         If FoundFilenames.Count = 0 Then
  94.             cell.Value = $" { FileNameToBeFound} not found in { Title_SelectedFloder}"
  95.             Excel_Application.ActiveWindow.DisplayGridlines = False
  96.             Exit Sub
  97.         End If
  98.         cell.Value =
  99.             $"  Find {FoundFilenames.Count} { FileNameToBeFound} in { Title_SelectedFloder}"
  100.         cell = cell.Offset(1, 0)
  101.         FoundFilenames.Sort(AddressOf Me.Comparer_Folder_Item)
  102.         Call ColumnName()
  103.         For Each Folder_Item As FolderItem In FoundFilenames
  104.             Call ColumnValue(Folder_Item)
  105.         Next
  106.     End Sub
  107.     Sub Show_ModifyFolderItem(Title_SelectedFolder As String)
  108.         Dim ModifiedFolderItems As Collections.Generic.List(Of FolderItem) =
  109.             Me.Find_files.ModifiedFolderItems
  110.         InitializeWorksheet("Modified files")
  111.         Dim Str As String
  112.         If ModifiedFolderItems.Count = 0 Then
  113.             Str = "there is no file"
  114.             Excel_Application.ActiveWindow.DisplayGridlines = False
  115.         ElseIf ModifiedFolderItems.Count = 1 Then
  116.             Str = "there is 1 file"
  117.         Else
  118.             Str = $"there are {ModifiedFolderItems.Count} files"
  119.         End If
  120.         cell.Value = $" From { Time_UpLimitation:yyyy/MM/dd HH:mm:ss}" &
  121.                      $" to { Time_DownLimitation:yyyy/MM/dd HH:mm:ss}, " &
  122.                      $"{Str} being modified in { Title_SelectedFolder}"
  123.         If ModifiedFolderItems.Count = 0 Then Exit Sub
  124.         cell = cell.Offset(1, 0)
  125.         ModifiedFolderItems.Sort(AddressOf Me.Comparer_Folder_Item)
  126.         Call ColumnName()
  127.         For Each Folder_Item As FolderItem In ModifiedFolderItems
  128.             Call ColumnValue(Folder_Item)
  129.         Next
  130.     End Sub
  131.     Sub Show_Like_Filename_BeFound(Title_SelectedFolder As String)
  132.         Dim Like_Filenames_BeFound As Collections.Generic.List(Of FolderItem) =
  133.             Me.Find_files.Like_Filenames_BeFound
  134.         InitializeWorksheet("Like filename")
  135.         If Like_Filenames_BeFound.Count = 0 Then
  136.             cell.Value = $" No file like { Like_FileNameToBeFound} has been found" &
  137.                          $" in { Title_SelectedFolder}"
  138.             Excel_Application.ActiveWindow.DisplayGridlines = False
  139.             Exit Sub
  140.         End If
  141.         cell.Value = $"  Find {Like_Filenames_BeFound.Count} files with name like { Like_FileNameToBeFound}" &
  142.                          $" in { Title_SelectedFolder}"
  143.         cell = cell.Offset(1, 0)
  144.         Like_Filenames_BeFound.Sort(AddressOf Me.Comparer_Folder_Item)
  145.         Call ColumnName()
  146.         For Each Folder_Item As FolderItem In Like_Filenames_BeFound
  147.             Call ColumnValue(Folder_Item)
  148.         Next
  149.     End Sub


  150.     Const CountOfColumnsToBeAccess As Int32 = 10
  151.     Private Sub Set_FontColor_Depending_on_Dir(Folder_Item As FolderItem)
  152.         Static previous_dir_name As String
  153.         Static ColorSwitch As Boolean
  154.         Dim Dir_Name As String = My.Computer.FileSystem.GetParentPath(Folder_Item.Path)
  155.         If String.Compare(Dir_Name, previous_dir_name) <> 0 Then
  156.             ColorSwitch = Not ColorSwitch
  157.             previous_dir_name = Dir_Name
  158.         End If
  159.         Worksheet.Range(cell, cell.Offset(0, CountOfColumnsToBeAccess)).Font.ColorIndex =
  160.              CInt(If(ColorSwitch, 10, 5))
  161.     End Sub
  162.     Const Const_Directery As String = "___"
  163.     Protected Function Comparer_Folder_Item(x As FolderItem, y As FolderItem) As Integer
  164.         Dim X1 As String
  165.         Dim Y1 As String
  166.         If String.IsNullOrEmpty(x.Path) Then
  167.             X1 = Const_Directery
  168.         Else
  169.             X1 = My.Computer.FileSystem.GetParentPath(x.Path)
  170.         End If
  171.         If String.IsNullOrEmpty(y.Path) Then
  172.             Y1 = Const_Directery
  173.         Else
  174.             Y1 = My.Computer.FileSystem.GetParentPath(y.Path)
  175.         End If
  176.         If X1 > Y1 Then Return 1
  177.         If X1 < Y1 Then Return -1
  178.         Return String.Compare(x.Name, y.Name, ignoreCase:=True)
  179.     End Function
  180.     Sub ColumnName()
  181.         Dim R As Range = cell
  182.         With Worksheet.Range(R, R.Offset(0, CountOfColumnsToBeAccess))
  183.             .HorizontalAlignment = Excel.Constants.xlCenter
  184.             .Font.ColorIndex = 3
  185.         End With

  186.         R.ColumnWidth = 4 * CDbl(R.ColumnWidth)
  187.         R.Value = "File name" : R = R.Next

  188.         R.Value = "LastWriteTime" : R = R.Next
  189.         R.Value = "LastAccessTime" : R = R.Next
  190.         R.Value = "CreationTime" : R = R.Next
  191.         R.Value = "Length" : R = R.Next

  192.         R.ColumnWidth = 21 * CDbl(R.ColumnWidth)
  193.         R.HorizontalAlignment = Excel.Constants.xlLeft
  194.         R.Value = "Directory" : R = R.Next

  195.         cell = cell.Offset(RowOffset:=1, ColumnOffset:=0)
  196.     End Sub
  197.     Sub ColumnValue(Folder_Item As FolderItem)
  198.         Dim FileInfo As IO.FileInfo
  199.         Try
  200.             FileInfo = My.Computer.FileSystem.GetFileInfo(Folder_Item.Path)
  201.             Set_FontColor_Depending_on_Dir(Folder_Item)
  202.             Dim R As Range = cell
  203.             With R
  204.                 .Value = FileInfo.Name                             ' 0
  205.             End With : R = R.Next

  206.             With R
  207.                 .Value = FileInfo.LastWriteTime                    ' 1
  208.                 .NumberFormatLocal = "yyyy/MM/dd HH:mm:ss"
  209.             End With : R = R.Next

  210.             With R
  211.                 .Value = FileInfo.LastAccessTime                   ' 2
  212.                 .NumberFormatLocal = "yyyy/MM/dd HH:mm:ss"
  213.             End With : R = R.Next

  214.             With R
  215.                 .Value = FileInfo.CreationTime                      ' 3
  216.                 .NumberFormatLocal = "yyyy/MM/dd HH:mm:ss"
  217.             End With : R = R.Next

  218.             With R
  219.                 .Value = FileInfo.Length                           ' 4
  220.             End With : R = R.Next

  221.             With R
  222.                 .Value = $"{FileInfo.DirectoryName}"               ' 5 
  223.             End With : R = R.Next

  224.         Catch e As Exception

  225.         Finally
  226.             cell = cell.Offset(1, 0)
  227.         End Try
  228.     End Sub
  229. End Class

























  •   <setting name="Button2Text" serializeAs="String">
  •       <value>Selected folder</value>
  •   </setting>
  •   <setting name="CheckBox1Text" serializeAs="String">
  •       <value>FileName</value>
  •   </setting>
  •   <setting name="CheckBox2Text" serializeAs="String">
  •       <value>Modified time</value>
  •   </setting>
  •   <setting name="CheckBox3Text" serializeAs="String">
  •       <value>Like-fileName</value>
  •   </setting>
  •   <setting name="DateTimeFormat" serializeAs="String">
  •       <value>yyyy/MM/dd HH:mm:ss</value>
  •   </setting>
  •   <setting name="Form1Text" serializeAs="String">
  •       <value>Find files in a selected folder</value>
  •   </setting>



  •  <setting name="Form1Position" serializeAs="String">
  •      <value>100,100,1500,1000</value>
  •  </setting>
  •  <setting name="SelectedPath" serializeAs="String">
  •      <value>C:\Windows\System32</value>
  •  </setting>
  •  <setting name="Like_FilenameToBeFound" serializeAs="String">
  •      <value>*.txt</value>
  •  </setting>
  •  <setting name="FilenameToBeFound" serializeAs="String">
  •      <value>Notepad.exe</value>
  •  </setting>
  •  <setting name="Bool_Find_Filename" serializeAs="String">
  •      <value>true</value>
  •  </setting>
  •  <setting name="Bool_Like_Filename" serializeAs="String">
  •      <value>true</value>
  •  </setting>
  •  <setting name="Bool_Modified_Files" serializeAs="String">
  •      <value>true</value>
  •  </setting>


  • <System.Windows.Forms.ApplicationConfigurationSection>
  • <add key="DpiAwareness" value="PerMonitorV2" />
  • <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
  • </System.Windows.Forms.ApplicationConfigurationSection>

























留言

這個網誌中的熱門文章

Marshalling

Calling a C# WPF library from C++

Marshalling II