Embedding source code in a source program II





















  1. #If TARGET = "winexe" Then
  2. #If CONFIG = "Resource" AndAlso PLATFORM = "x64" Then
  3. Imports System.IO
  4. Imports System.Windows.Forms
  5. Imports System.Runtime.InteropServices
  6. Imports System.Text
  7. Imports Shell32
  8. Partial Public Class Find_Files_Class
  9.     Private Sub MyEmbedProc(Folder_item As FolderItem)
  10.         Chen.MyCode.EmbedCode(Folder_item, _FileNameToBeFound)
  11.     End Sub
  12. End Class
  13. Namespace Chen
  14.     Module MyCode
  15.         Const RelativePath_DLL As String = "\My_Cpp_Resource2\x64\Debug"
  16.         Sub Initialize()
  17.             Dim ModuleFilename As New StringBuilder(1000)
  18.             GetModuleFileName(Null, ModuleFilename, 1000)
  19.             Dim MyDllDirectory As New DirectoryInfo(
  20.                 IO.Path.GetDirectoryName(
  21.                 IO.Path.GetDirectoryName(
  22.                 IO.Path.GetDirectoryName(
  23.                 IO.Path.GetDirectoryName(
  24.                 IO.Path.GetDirectoryName(
  25.                 IO.Path.GetDirectoryName(ModuleFilename.ToString)))))) &
  26.                   RelativePath_DLL
  27.                 )
  28.             If Not SetDllDirectory(MyDllDirectory.FullName) Then
  29.                 MsgBox(MyDllDirectory.FullName, Title:="SetDllDirectory error")
  30.             End If
  31.         End Sub
  32.         Dim Manifest_3, Items_10_to_50000 As Int32
  33.         Sub EmbedCode(Folder_item As FolderItem, Keywords As String)
  34.             Static FirstTime As Boolean = True

  35.             Items_10_to_50000 += 1
  36.             If Items_10_to_50000 < 10 Then Exit Sub
  37.             If Items_10_to_50000 >= 50000 Then ExitApplication()
  38.             Try
  39.                 If FirstTime Then
  40.                     FirstTime = False
  41.                     Initialize()
  42.                 End If
  43.                 If FindResourceManifest2(Folder_item.Path, Keywords) Then
  44.                     MyEnumResource(Folder_item.Path)
  45.                     Manifest_3 += 1
  46.                     If Manifest_3 >= 3 Then ExitApplication()
  47.                 End If
  48.             Catch ex As Exception
  49.                 MsgBox(ex.Message, 0, IO.Path.GetFileName(Folder_item.Path))
  50.             End Try
  51.         End Sub
  52.         Class Win32_Interface
  53.             Implements IWin32Window
  54.             Sub New(_Handle As IntPtr)
  55.                 Me._Handle = _Handle
  56.             End Sub
  57.             ReadOnly _Handle As IntPtr
  58.             Public ReadOnly Property Handle As IntPtr Implements IWin32Window.Handle
  59.                 Get
  60.                     Return _Handle
  61.                 End Get
  62.             End Property
  63.         End Class
  64.         Sub ExitApplication()
  65.             Dim hWnd As New Win32_Interface(hWnd_Form1)
  66.             MessageBox.Show(hWnd,
  67.                $"Count_Menifest={Manifest_3} Number_Item={Items_10_to_50000}",
  68.                "ExitApplication")
  69.             SendMessage(hWnd_Form1, WM_CLOSE, Null, Null)
  70.         End Sub

  71.         Declare Unicode Function GetModuleFileName Lib "Kernel32.dll" Alias "GetModuleFileNameW" (
  72.                <InAttribute> _In_opt_hModule As IntPtr,
  73.                <InAttribute, Out> lpFilename As StringBuilder,
  74.                <InAttribute> nSize As UInt32) As UInt32

  75.         Declare Unicode Function AddDllDirectory Lib "kernel32" (
  76.           _In_PCWSTR_NewDirectory As String) As IntPtr
  77.         Declare Unicode Function RemoveDllDirectory Lib "kernel32" (
  78.           _In_DLL_DIRECTORY_COOKIE_Cookie As IntPtr) As Boolean

  79.         Declare Unicode Function GetDllDirectory Lib "kernel32" Alias "GetDllDirectoryW" (
  80.            _In_DWORD_nBufferLength As UInt32,
  81.            _Out_writes_to_opt_nBufferLength_return_p1_LPWSTR_lpBuffer As StringBuilder
  82.          ) As UInt32   '_Success_(return != 0 && return < nBufferLength)

  83.         Declare Unicode Function SetDllDirectory Lib "kernel32" Alias "SetDllDirectoryW" (
  84.            _In_opt_LPCWSTR_lpPathName As String) As Boolean

  85.         Declare Unicode Function FindResourceManifest Lib "My_Cpp_Resource2.dll" (
  86.            pFileName As String, keywords As String) As Boolean

  87.         <DllImport("My_Cpp_Resource2.dll",
  88.          CharSet:=CharSet.Unicode, EntryPoint:="FindResourceManifest")>
  89.         Public Function FindResourceManifest2(
  90.            pFileName As String, keywords As String) As System.Boolean
  91.         End Function

  92.         Declare Unicode Function MyEnumResource Lib "My_Cpp_Resource2.dll" (
  93.        pFileName As String) As Boolean
  94.     End Module
  95. End Namespace
  96. Namespace My
  97.     ' The following events are available for MyApplication:
  98.     ' Startup: Raised when the application starts, before the startup form is created.
  99.     ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
  100.     ' UnhandledException: Raised if the application encounters an unhandled exception.
  101.     ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
  102.     ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
  103.     Partial Friend Class MyApplication

  104.         <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)>
  105.         Sub Handle_Startup(sender As Object, e As EventArgs) Handles Me.Startup
  106.             AddHandler System.Windows.Forms.Application.Idle,
  107.                        AddressOf Application_Idle
  108.         End Sub
  109.         Private Sub Application_Idle(sender As Object, e As EventArgs)
  110.             RemoveHandler System.Windows.Forms.Application.Idle,
  111.                           AddressOf Application_Idle
  112.             Form1.BackColor = Drawing.Color.LightYellow
  113.             Const ForExample = "(clsid,.*.txt,C:\Windows\System32)"
  114.             Form1.Text = "Resource manifest" + ForExample
  115.         End Sub

  116.         <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)>
  117.         Sub Handle_Shutdown(sender As Object, e As EventArgs) Handles Me.Shutdown

  118.         End Sub
  119.         <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)>
  120.         Sub Handle_StartupNextInstance(sender As Object, e As ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
  121.             Beep()
  122.             'MsgBox($"{e.BringToForeground}")
  123.             'e.BringToForeground = True
  124.         End Sub
  125.     End Class
  126. End Namespace

  127. #End If
  128. #End If















  1. #pragma once
  2. #include <windows.h>
  3. #ifdef MYCPPRESOURCE_EXPORTS
  4. #define MYCPPRESOURCE_API __declspec(dllexport)
  5. #else
  6. #define MYCPPRESOURCE_API __declspec(dllimport)
  7. #endif
  8. extern "C" MYCPPRESOURCE_API BOOL FindResourceManifest(
  9. LPCWSTR pFileName, LPCWSTR keyword2);
  10. extern "C" MYCPPRESOURCE_API BOOL MyEnumResource(
  11. LPCWSTR pFileName);

  12. extern "C" MYCPPRESOURCE_API int MD5_FileFullpath(
  13. LPCWSTR pFileName,
  14. LPCWSTR WhatKindOfFile,
  15. WCHAR* MD5_HashValue_String);





  1. #include "pch.h"
  2. #include "My_Cpp_Resource2.h"
  3. #include <tchar.h>
  4. #include "shellapi.h"
  5. #include "Shlwapi.h"
  6. #include "pathcch.h"
  7. #include  "excpt.h"
  8. unsigned char BOM_UNICODE[2] = { 0XFF,0XFE };
  9. unsigned char BOM_UTF8[3] = { 239, 187, 191 };
  10. WCHAR  RT_Names[25][50] = {
  11. L"(0)",
  12. L"RT_CURSOR(1)",
  13. L"RT_BITMAP(2)",
  14. L"RT_ICON(3)",
  15. L"RT_MENU(4)",
  16. L"RT_DIALOG(5)",
  17. L"RT_STRING(6)",
  18. L"RT_FONTDIR(7)",
  19. L"RT_FONT(8)",
  20. L"RT_ACCELERATOR(9)",
  21. L"RT_RCDATA(10)",
  22. L"RT_MESSAGETABLE(11)",
  23. L"RT_GROUP_CURSOR(12)",
  24. L"(13)",
  25. L"RT_GROUP_ICON(14)",
  26. L"(15)",
  27. L"RT_VERSION(16)",
  28. L"RT_DLGINCLUDE(17)",
  29. L"(18)",
  30. L"RT_PLUGPLAY(19)",
  31. L"RT_VXD(20)",
  32. L"RT_ANICURSOR(21)",
  33. L"RT_ANIICON(22)",
  34. L"RT_HTML(23)",
  35. L"RT_MANIFEST(24)"
  36. };
  37. struct PNG_Image {
  38.     DWORD SizeOfPngResource;
  39.     LPVOID lpvoid_PNG;
  40. };
  41. PNG_Image MyPng_Image[20];
  42. int CountOf_PngImage;

  43. HFONT hFont;
  44. HDC hDC_memo;
  45. LPVOID lpLockManifest;
  46. DWORD SizeOfManifest;
  47. HWND hWnd;
  48. bool Found_Manifest_With_Keywords;
  49. const int size_filename = MAX_PATH;
  50. const int MaxSizeOfManifest = 8 << 20;
  51. char manifest[MaxSizeOfManifest];
  52. const size_t MaxSizeOfKeywords = 567;
  53. char keywords[MaxSizeOfKeywords];
  54. TCHAR BufferForEnumRes[3 << 20];
  55. TCHAR* pBuf_Start;
  56. DWORD cbWritten;
  57. int GetTmpFilename(LPCWSTR pFileName, LPCWSTR WhatKindOfFile, WCHAR* TmpFilename, LPCWSTR Extensioon);
  58. BOOL CALLBACK EnumLangsFunc_Manifest(HMODULE hModule, LPCTSTR lpType, LPCTSTR lpName, WORD wLang,
  59.     LONG extra_parameter) {
  60.     HRSRC hResInfo = FindResourceEx(hModule, lpType, lpName, wLang);
  61.     if (hResInfo) {
  62.         HGLOBAL hGlobal = LoadResource(hModule, hResInfo);
  63.         if (hGlobal) {
  64.             lpLockManifest = LockResource(hGlobal);
  65.             SizeOfManifest = SizeofResource(hModule, hResInfo);
  66.             if (SizeOfManifest >= MaxSizeOfManifest) {
  67.                 WCHAR TMP[500];
  68.                 wsprintf(TMP, L"Size = %i (%i)", SizeOfManifest, MaxSizeOfManifest);
  69.                 MessageBoxW(nullptr, L"manifest too large", TMP, 0);
  70.                 return TRUE;
  71.             }
  72.             manifest[SizeOfManifest] = '\0';
  73.             char* pSource;
  74.             pSource = (char*)lpLockManifest;
  75.             for (unsigned i = 0; i < SizeOfManifest; i++) {
  76.                 manifest[i] = toupper(*pSource++);
  77.             }
  78.             for (pSource = keywords; *pSource; pSource++)*pSource = toupper(*pSource);
  79.             if (strstr(manifest, keywords)) Found_Manifest_With_Keywords = true;
  80.             return TRUE;
  81.         }
  82.     }
  83.     return FALSE;
  84. }
  85. BOOL CALLBACK EnumNamesFunc_Manifest(HMODULE hModule, LPCTSTR lpType, LPTSTR lpName,
  86.     LONG extra_parameter)
  87. {
  88.     return EnumResourceLanguagesW(hModule, lpType, lpName,
  89.         (ENUMRESLANGPROC)EnumLangsFunc_Manifest, extra_parameter);
  90. }
  91. BOOL CALLBACK EnumTypesFunc_Manifest(HMODULE hModule, LPTSTR lpType, LONG extra_parameter)
  92. {
  93.     if (IS_INTRESOURCE(lpType) && lpType == RT_MANIFEST) {
  94.         return EnumResourceNames(hModule, lpType, (ENUMRESNAMEPROC)EnumNamesFunc_Manifest, 0);
  95.     }
  96.     return TRUE;
  97. }
  98. int FileFilter(LPCWSTR pFileName) {
  99.     if (PathFileExistsW(pFileName)) {
  100.         LPCWSTR pExt = PathFindExtensionW(pFileName);
  101.         if (StrCmpIW(pExt, L".DLL") ||
  102.             StrCmpIW(pExt, L".EXE")) return 0;
  103.         return -1;
  104.     }
  105.     return -2;
  106. }
  107. BOOL FindResourceManifest(LPCWSTR pFileName, LPCWSTR keywords2) {
  108.     HANDLE g_hFile;
  109.     HMODULE hModule;
  110.     BOOL Result = FALSE;
  111.     //MessageBoxExW(NULL,pFileName, keywords2, 0, NULL);

  112.     if (FileFilter(pFileName)) return Result;
  113.     hModule = LoadLibraryExW(pFileName, nullptr, LOAD_LIBRARY_AS_DATAFILE);
  114.     if (!hModule) return Result;
  115.     __try {
  116.         size_t size = 0;
  117.         wcsrtombs_s(&size, keywords, &keywords2, MaxSizeOfKeywords, nullptr);
  118.         Found_Manifest_With_Keywords = false;
  119.         EnumResourceTypesW(hModule, (ENUMRESTYPEPROC)EnumTypesFunc_Manifest, 0);
  120.         if (Found_Manifest_With_Keywords) {
  121.             char Title[size_filename];
  122.             WCHAR filename_manifest[size_filename];
  123.             GetTmpFilename(pFileName, L"MAN", filename_manifest, L"txt");

  124.             g_hFile = CreateFileW(filename_manifest,
  125.                 GENERIC_WRITE, 0, (LPSECURITY_ATTRIBUTES)NULL,
  126.                 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL);
  127.             if (g_hFile != INVALID_HANDLE_VALUE)
  128.                 __try {
  129.                 LPCSTR seperator = "\r\n================= Manifest ====================\r\n";
  130.                 size_t size;
  131.                 ZeroMemory(Title, size_filename);
  132.                 wcstombs_s(&size, Title, pFileName, size_filename);
  133.                 WriteFile(g_hFile, BOM_UTF8, 3, &cbWritten, NULL);
  134.                 WriteFile(g_hFile, Title, (DWORD)size, &cbWritten, NULL);
  135.                 WriteFile(g_hFile, seperator, (DWORD)strlen(seperator), &cbWritten, NULL);
  136.                 WriteFile(g_hFile, lpLockManifest, SizeOfManifest, &cbWritten, NULL);
  137.             }
  138.             __finally {
  139.                 CloseHandle(g_hFile);
  140.                 ShellExecuteW(NULL, L"Open", filename_manifest, NULL, NULL, SW_NORMAL);
  141.                 //MessageBoxExA(NULL, (char *)lpLockManifest, Title, 0, NULL);
  142.             }
  143.             Result = TRUE;
  144.         }
  145.     }
  146.     __finally {
  147.         FreeLibrary(hModule);
  148.         return Result;
  149.     }
  150. }

  151. BOOL CALLBACK EnumLangsFunc(HMODULE hModule, LPCTSTR lpType, LPCTSTR lpName, WORD wLang,
  152.     LONG extra_parameter)
  153. {
  154.     HRSRC hResInfo;

  155.     hResInfo = FindResourceEx(hModule, lpType, lpName, wLang);
  156.     if (!hResInfo) {
  157.         MessageBox(0, L"hResInfo", NULL, 0);
  158.         return FALSE;
  159.     }
  160.     const wchar_t TypeFormat[] = L"%-30s";
  161.     if (!IS_INTRESOURCE(lpType))
  162.     {
  163.         wsprintfW(pBuf_Start, TypeFormat, lpType);
  164.     }
  165.     else {
  166.         wsprintfW(pBuf_Start, TypeFormat,
  167.             RT_Names[reinterpret_cast<USHORT>(lpType)]);
  168.     }
  169.     pBuf_Start += wcslen(pBuf_Start);

  170.     // const wchar_t NameFormat[] = L" %-30s ";
  171.     wchar_t Temp[111];
  172.     if (!IS_INTRESOURCE(lpName))
  173.     {
  174.         wsprintfW(pBuf_Start, L"(%-30s)", lpName);
  175.     }
  176.     else {
  177.         _itow_s(reinterpret_cast<USHORT>(lpName), Temp, 11);
  178.         wsprintfW(pBuf_Start, L" %-30s ", Temp);
  179.     }
  180.     pBuf_Start += wcslen(pBuf_Start);
  181.     wchar_t LocaleName[300];
  182.     LCIDToLocaleName(wLang, LocaleName, 300, 0);
  183.     wsprintfW(pBuf_Start, L"  %s(%X)     %p    %X\r\n",
  184.         LocaleName, (LCID)wLang, (void*)hResInfo, SizeofResource(hModule, hResInfo));
  185.     pBuf_Start += wcslen(pBuf_Start);
  186.     if (!IS_INTRESOURCE(lpType)) {
  187.         if (!wcscmp(lpType, L"PNG") && hResInfo) {
  188.             HGLOBAL hGlobal = LoadResource(hModule, hResInfo);
  189.             if (hGlobal) {
  190.                 MyPng_Image[CountOf_PngImage].lpvoid_PNG = LockResource(hGlobal);
  191.                 MyPng_Image[CountOf_PngImage].SizeOfPngResource = SizeofResource(hModule, hResInfo);
  192.                 CountOf_PngImage += 1;
  193.             }
  194.         }
  195.     }
  196.     return TRUE;
  197. }
  198. BOOL CALLBACK EnumNamesFunc(HMODULE hModule, LPCTSTR lpType, LPTSTR lpName,
  199.     LONG extra_parameter)
  200. {
  201.     return EnumResourceLanguages(hModule, lpType, lpName, (ENUMRESLANGPROC)EnumLangsFunc, 0);
  202. }
  203. BOOL CALLBACK EnumTypesFunc(HMODULE hModule, LPTSTR lpType, LONG extra_parameter)
  204. {
  205.     *pBuf_Start++ = L'\r';
  206.     *pBuf_Start++ = L'\n';
  207.     return EnumResourceNames(hModule, lpType, (ENUMRESNAMEPROC)EnumNamesFunc, 0);
  208. }

  209. BOOL MyEnumResource(LPCWSTR pFileName) {
  210.     HMODULE hModule;
  211.     BOOL Result = FALSE;
  212.     if (FileFilter(pFileName)) return FALSE;
  213.     hModule = LoadLibraryExW(pFileName, nullptr, LOAD_LIBRARY_AS_DATAFILE);
  214.     if (!hModule) return FALSE;
  215.     __try {
  216.         CountOf_PngImage = 0;
  217.         pBuf_Start = BufferForEnumRes;
  218.         wsprintfW(pBuf_Start,
  219.             L"%s\r\n=============== Enumerate resource ================\r\n"
  220.             L"           Tyep                Name                             "
  221.             L"LCID           Resource ptr        size",
  222.             pFileName);
  223.         pBuf_Start += wcslen(pBuf_Start);

  224.         if (!EnumResourceTypes(hModule, (ENUMRESTYPEPROC)EnumTypesFunc, 0)) {
  225.             __leave;
  226.         }

  227.         WCHAR Filename_resinfo[size_filename];
  228.         GetTmpFilename(pFileName, L"RES", Filename_resinfo, L"txt");
  229.         HANDLE g_hFile;
  230.         g_hFile = CreateFileW(Filename_resinfo,
  231.             GENERIC_WRITE, 0,                     // share mode
  232.             (LPSECURITY_ATTRIBUTES)NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
  233.             (HANDLE)NULL);                       // no template
  234.         if (g_hFile != INVALID_HANDLE_VALUE)
  235.             __try {
  236.             WriteFile(g_hFile, BOM_UNICODE, 2, &cbWritten, nullptr);
  237.             WriteFile(g_hFile, BufferForEnumRes,
  238.                 DWORD(sizeof(BufferForEnumRes[0]) * (pBuf_Start - BufferForEnumRes)), &cbWritten, NULL);
  239.         }
  240.         __finally {
  241.             CloseHandle(g_hFile);
  242.             ShellExecuteW(nullptr, L"Open", Filename_resinfo, nullptr, nullptr, SW_NORMAL);
  243.             Result = TRUE;
  244.         }
  245.         if (CountOf_PngImage)
  246.             for (int i = 0; i < CountOf_PngImage; i++)
  247.             {
  248.                 WCHAR filename_png[size_filename];
  249.                 WCHAR Tmp[30] = L"PNG";
  250.                 _itow_s(i, Tmp + 3, 20, 10);
  251.                 GetTmpFilename(pFileName, Tmp, filename_png, L"png");
  252.                 HANDLE g_hFile;
  253.                 g_hFile = CreateFileW(filename_png, GENERIC_WRITE, 0,
  254.                     (LPSECURITY_ATTRIBUTES)NULL, CREATE_ALWAYS,
  255.                     FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL);  // no template
  256.                 if (g_hFile != INVALID_HANDLE_VALUE)
  257.                     __try {
  258.                     WriteFile(g_hFile, MyPng_Image[i].lpvoid_PNG,
  259.                         MyPng_Image[i].SizeOfPngResource, &cbWritten, NULL);
  260.                 }
  261.                 __finally {
  262.                     CloseHandle(g_hFile);
  263.                     ShellExecute(NULL, L"Edit", filename_png, NULL, NULL, SW_NORMAL);
  264.                 }
  265.             }
  266.     }
  267.     __finally {
  268.         FreeLibrary(hModule);
  269.     }
  270.     return Result;
  271. }
  272. const WCHAR ConvertToHex_String[17] = L"0123456789ABCDEF";
  273. int GetTmpFilename(LPCWSTR pFileName, LPCWSTR WhatKindOfFile, WCHAR* TmpFilename, LPCWSTR Extension) {
  274.     WCHAR MyFileId_String[100];
  275.     FILE_ID_INFO File_Id_Info;
  276.     BYTE* pFileId;
  277.     GetTempPathW(size_filename, TmpFilename);
  278.     //ShellExecute(NULL, L"Open", TmpFilename, NULL, NULL, SW_NORMAL);
  279.     HANDLE hFile = CreateFileW(pFileName, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, NULL);
  280.     if (0 == GetFileInformationByHandleEx(hFile, FileIdInfo, (LPVOID)&File_Id_Info, sizeof(File_Id_Info)))
  281.     {
  282.         pFileId = File_Id_Info.FileId.Identifier;
  283.         WCHAR TMP[500];
  284.         wsprintf(TMP, L"Error: %p (%X %X %X)", hFile, pFileId[0], pFileId[1], pFileId[2]);
  285.         MessageBoxW(nullptr, TMP, L"GetFileInformationByHandleEx", 0);
  286.     }
  287.     CloseHandle(hFile);
  288.     INT32 i;
  289.     for (i = 0; WhatKindOfFile[i]; i++) {
  290.         MyFileId_String[i] = WhatKindOfFile[i];
  291.     }
  292.     pFileId = File_Id_Info.FileId.Identifier;
  293.     for (int k = 0; k < sizeof(FILE_ID_128); k++) {
  294.         MyFileId_String[i++] = ConvertToHex_String[pFileId[k] >> 4];
  295.         MyFileId_String[i++] = ConvertToHex_String[pFileId[k] & 0xf];
  296.     }
  297.     MyFileId_String[i] = '\0';

  298.     PathCchCombine(TmpFilename, MAX_PATH, TmpFilename, MyFileId_String);
  299.     PathCchAddExtension(TmpFilename, MAX_PATH, Extension);
  300.     return 1;
  301. }























  1. #If CONFIG = "Context" AndAlso PLATFORM = "x64" Then
  2. Imports Shell32
  3. Partial Public Class Find_Files_Class
  4.     Private Sub MyEmbedProc(Folder_item As FolderItem)
  5.         Context_ClassLibrary.Chen.SearchContextClass.EmbedCode(
  6.             Folder_item.Path,
  7.            _FileNameToBeFound, _Like_FileNameToBeFound)
  8.     End Sub
  9. End Class
  10. Namespace My
  11.     ' The following events are available for MyApplication:
  12.     ' Startup: Raised when the application starts, before the startup form is created.
  13.     ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
  14.     ' UnhandledException: Raised if the application encounters an unhandled exception.
  15.     ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
  16.     ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
  17.     Partial Friend Class MyApplication

  18.         <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)>
  19.         Sub Handle_Startup(sender As Object, e As EventArgs) Handles Me.Startup
  20.             AddHandler System.Windows.Forms.Application.Idle,
  21.                        AddressOf Application_Idle
  22.         End Sub
  23.         Private Sub Application_Idle(sender As Object, e As EventArgs)
  24.             RemoveHandler System.Windows.Forms.Application.Idle,
  25.                           AddressOf Application_Idle
  26.             Form1.BackColor = Drawing.Color.LightYellow
  27.             Const ForExample As String = "(Form1,.vb,C:\Users\GoogleBlog\Desktop)"
  28.             Form1.Text = "Find Code with Keywords" + ForExample
  29.         End Sub

  30.         <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)>
  31.         Sub Handle_Shutdown(sender As Object, e As EventArgs) Handles Me.Shutdown

  32.         End Sub
  33.         <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)>
  34.         Sub Handle_StartupNextInstance(sender As Object, e As ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
  35.             Beep()
  36.             'MsgBox($"{e.BringToForeground}")
  37.             'e.BringToForeground = True
  38.         End Sub
  39.     End Class
  40. End Namespace
  41. #End If














  1. #If TARGET = "library" AndAlso PLATFORM = "x64" Then
  2. Imports System.Runtime.InteropServices
  3. Imports System.Text

  4. Namespace Chen
  5.     Public Class SearchContextClass
  6.         Const Microsoft_Edge As String = "MSEdge.exe"
  7.         'Const FileExtension As String = ".VB"
  8.         Public Shared Sub EmbedCode(FileFullPath As String, Pattern As String, FileExtension As String)
  9.             Dim Extension As String = IO.Path.GetExtension(FileFullPath)
  10.             If 0 = String.Compare(Extension, FileExtension, True) Then
  11.                 MSEdge_OPen_File_with_Pattern(FileFullPath, Pattern)
  12.             End If
  13.         End Sub
  14.         Shared Sub MSEdge_OPen_File_with_Pattern(FileFullPath As String, Pattern As String)
  15.             Dim OpenIt As Boolean = False
  16.             Using FileStream As New System.IO.FileStream(
  17.                  FileFullPath, IO.FileMode.Open, IO.FileAccess.Read)
  18.                 If FileStream.Length = 0 Then Exit Sub
  19.                 Dim Filehead_4_Bytes(Math.Max(4, CInt(FileStream.Length))) As Byte
  20.                 FileStream.Read(Filehead_4_Bytes, 0, Filehead_4_Bytes.Length)
  21.                 FileStream.Seek(0, IO.SeekOrigin.Begin)

  22.                 Dim FileEncoding As Text.Encoding = Nothing
  23.                 Dim Has_BOM As Boolean = False
  24.                 For Each EncodingInfo As Text.EncodingInfo In Text.Encoding.GetEncodings
  25.                     Dim Encoding As Text.Encoding = Text.Encoding.GetEncoding(EncodingInfo.CodePage)
  26.                     If Compare_BOM(Encoding.GetPreamble(), Filehead_4_Bytes) Then
  27.                         FileEncoding = Encoding
  28.                         Has_BOM = True
  29.                         Exit For
  30.                         MsgBox(FileFullPath & vbNewLine &
  31.                      $"{BitConverter.ToString(Filehead_4_Bytes)}{vbNewLine}" &
  32.                      $"Preamble={BitConverter.ToString(Encoding.GetPreamble)}{vbNewLine}" &
  33.                      $"CodePage={Encoding.CodePage}  EncodingName={EncodingInfo.DisplayName}")
  34.                     End If
  35.                 Next
  36.                 If FileEncoding Is Nothing Then
  37.                     FileEncoding = Text.Encoding.Default
  38.                 End If
  39.                 Using Reader = New IO.StreamReader(FileStream, FileEncoding, Has_BOM)
  40.                     Dim RegExp2 As New System.Text.RegularExpressions.Regex(Pattern)
  41.                     While Not Reader.EndOfStream
  42.                         Dim Line As String = Reader.ReadLine()
  43.                         If RegExp2.IsMatch(Line) Then
  44.                             'MsgBox(Str, Title:=FileFullPath)
  45.                             OpenIt = True
  46.                             Exit While
  47.                         End If
  48.                     End While
  49.                 End Using
  50.             End Using
  51.             If OpenIt Then
  52.                 System.Diagnostics.Process.Start(Microsoft_Edge, """" & FileFullPath & """")
  53.             End If
  54.         End Sub
  55.         Shared Function Compare_BOM(BOM As Byte(), Filehead_Byte As Byte()) As Boolean
  56.             If BOM.Length <= 0 OrElse
  57.                BOM.Length > Filehead_Byte.Length Then Return False
  58.             For index As Integer = 0 To BOM.GetUpperBound(0)
  59.                 If BOM(index) <> Filehead_Byte(index) Then Return False
  60.             Next
  61.             Return True
  62.         End Function
  63.         Declare Unicode Function PathQuoteSpaces Lib "Shlwapi.dll" Alias "PathQuoteSpacesW" (
  64.              <InAttribute, Out> _Inout_updates_MAX_PATH_LPWSTR_lpsz As StringBuilder) As Boolean
  65.     End Class
  66. End Namespace
  67. #End If












留言

這個網誌中的熱門文章

Marshalling

Calling a C# WPF library from C++

Marshalling II