From 2c02e10dd13e999ebda225ba09b3d928a3c9c672 Mon Sep 17 00:00:00 2001 From: uduki Date: Tue, 20 Oct 2026 11:29:58 +0900 Subject: [PATCH] =?UTF-8?q?=E6=A9=9F=E8=83=BD=E8=BF=BD=E5=8A=A0:=20Everyth?= =?UTF-8?q?ing=20IPC=20=E3=82=92=E5=88=A9=E7=94=A8=E3=81=97=E3=81=9F?= =?UTF-8?q?=E8=B6=85=E9=AB=98=E9=80=9F=E3=83=95=E3=82=A9=E3=83=AB=E3=83=80?= =?UTF-8?q?=E8=B5=B0=E6=9F=BB=E3=82=B5=E3=83=BC=E3=83=93=E3=82=B9=E3=82=92?= =?UTF-8?q?=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Everything が起動しているかを判定し、WM_COPYDATA 通信によって指定フォルダ配下の全ファイル・サブディレクトリを一括取得する EverythingSearchService を実装しました。 --- Services/EverythingSearchService.cs | 312 ++++++++++++++++++++++++++++ 1 file changed, 312 insertions(+) create mode 100644 Services/EverythingSearchService.cs diff --git a/Services/EverythingSearchService.cs b/Services/EverythingSearchService.cs new file mode 100644 index 0000000..840780a --- /dev/null +++ b/Services/EverythingSearchService.cs @@ -0,0 +1,312 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Windows.Interop; + +namespace GameLauncher.Services +{ + /// + /// 高速検索ソフト「Everything」のIPC (WM_COPYDATA) APIを利用して、 + /// 指定フォルダ配下の全ファイルおよびサブディレクトリを0.1秒未満で一括取得するサービス + /// + public class EverythingSearchService + { + #region □定数(Private) + private const int WM_COPYDATA = 0x004A; + private const int EVERYTHING_IPC_COPYDATA_QUERYW = 2; + private const uint EVERYTHING_IPC_ALLRESULTS = 0xFFFFFFFF; + private const uint EVERYTHING_IPC_FOLDER = 0x00000002; + private const uint EVERYTHING_IPC_DRIVE = 0x00000004; + private const uint PM_REMOVE = 0x0001; + #endregion + + #region □構造体(Private) + [StructLayout(LayoutKind.Sequential)] + private struct COPYDATASTRUCT + { + public IntPtr dwData; + public int cbData; + public IntPtr lpData; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct EVERYTHING_IPC_QUERYW_HEADER + { + public uint max_results; + public uint offset; + public uint reply_copydata_message; + public uint search_flags; + public IntPtr reply_hwnd; + } + + [StructLayout(LayoutKind.Sequential)] + private struct MSG + { + public IntPtr hwnd; + public uint message; + public IntPtr wParam; + public IntPtr lParam; + public uint time; + public int pt_x; + public int pt_y; + } + #endregion + + #region □メソッド(Public) + /// + /// Everything が現在システム上で実行中であるか判定します。 + /// + public static bool IsEverythingRunning() + { + try + { + var procs = Process.GetProcessesByName("Everything"); + if (procs != null && procs.Length > 0) + { + return true; + } + } + catch { } + + try + { + var hwnd = FindWindowW("EVERYTHING_TASKBAR_NOTIFICATION", null); + if (hwnd != IntPtr.Zero) + { + return true; + } + } + catch { } + + return false; + } + + /// + /// 指定されたパス群(例: C:\..., Z:\...)に対して、Everything IPCを用いて高速スナップショットを生成します。 + /// + /// 走査対象のディレクトリルート一覧 + /// タイムアウト(ミリ秒) + /// 生成されたスナップショット。Everything未稼働または失敗時は null + public static FastDirectorySnapshot? TryScanTargetsFast(IEnumerable targetDirectories, int timeoutMs = 3000) + { + var everythingHwnd = FindWindowW("EVERYTHING_TASKBAR_NOTIFICATION", null); + if (everythingHwnd == IntPtr.Zero) + { + return null; + } + + var snapshot = new FastDirectorySnapshot(); + bool anySuccess = false; + + foreach (var targetDir in targetDirectories) + { + if (string.IsNullOrWhiteSpace(targetDir)) continue; + string cleanDir = Path.GetFullPath(targetDir).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + + try + { + bool ok = QueryDirectory(everythingHwnd, cleanDir, snapshot, timeoutMs); + if (ok) + { + anySuccess = true; + } + } + catch + { + // 個別パスのクエリ失敗時はスキップ + } + } + + return anySuccess ? snapshot : null; + } + #endregion + + #region □メソッド(Private) + /// + /// Everything IPC を用いて1つのディレクトリ配下のファイル・フォルダ一覧を取得し、スナップショットに格納します。 + /// + private static bool QueryDirectory(IntPtr everythingHwnd, string targetDirectory, FastDirectorySnapshot snapshot, int timeoutMs) + { + bool success = false; + var resetEvent = new ManualResetEvent(false); + + // STAスレッド上でメッセージ受信用 HwndSource を作成 + var thread = new Thread(() => + { + HwndSource? source = null; + try + { + var parameters = new HwndSourceParameters("GameLauncher_Everything_Receiver") + { + Width = 0, + Height = 0, + PositionX = -100, + PositionY = -100, + WindowStyle = 0x800000 // WS_BORDER (非表示) + }; + source = new HwndSource(parameters); + source.AddHook((IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) => + { + if (msg == WM_COPYDATA) + { + var cds = Marshal.PtrToStructure(lParam); + if (cds.lpData != IntPtr.Zero && cds.cbData > 12) + { + ParseEverythingIpcList(cds.lpData, targetDirectory, snapshot); + success = true; + handled = true; + resetEvent.Set(); + } + } + return IntPtr.Zero; + }); + + // Everything への検索文字列構築(指定パス配下の全エントリ) + string searchQuery = $"path:\"{targetDirectory}\""; + + byte[] queryBytes = BuildQueryPayload(source.Handle, searchQuery); + GCHandle pinnedQuery = GCHandle.Alloc(queryBytes, GCHandleType.Pinned); + + try + { + var cdsSend = new COPYDATASTRUCT + { + dwData = (IntPtr)EVERYTHING_IPC_COPYDATA_QUERYW, + cbData = queryBytes.Length, + lpData = pinnedQuery.AddrOfPinnedObject() + }; + + SendMessage(everythingHwnd, WM_COPYDATA, source.Handle, ref cdsSend); + + // メッセージループを回して結果を待つ + var sw = Stopwatch.StartNew(); + while (sw.ElapsedMilliseconds < timeoutMs && !success) + { + while (PeekMessage(out var msg, IntPtr.Zero, 0, 0, PM_REMOVE)) + { + TranslateMessage(ref msg); + DispatchMessage(ref msg); + } + Thread.Sleep(5); + } + } + finally + { + if (pinnedQuery.IsAllocated) pinnedQuery.Free(); + } + } + catch + { + // クエリ処理中の例外 + } + finally + { + source?.Dispose(); + resetEvent.Set(); + } + }); + + thread.SetApartmentState(ApartmentState.STA); + thread.IsBackground = true; + thread.Start(); + + resetEvent.WaitOne(timeoutMs); + return success; + } + + /// + /// Everything IPC 送信用クエリバイナリペイロードを構築します。 + /// + private static byte[] BuildQueryPayload(IntPtr replyHwnd, string searchQuery) + { + var header = new EVERYTHING_IPC_QUERYW_HEADER + { + max_results = EVERYTHING_IPC_ALLRESULTS, + offset = 0, + reply_copydata_message = 0, + search_flags = 0, + reply_hwnd = replyHwnd + }; + + int headerSize = Marshal.SizeOf(typeof(EVERYTHING_IPC_QUERYW_HEADER)); + byte[] queryStrBytes = Encoding.Unicode.GetBytes(searchQuery + "\0"); + + byte[] payload = new byte[headerSize + queryStrBytes.Length]; + + IntPtr headerPtr = Marshal.AllocHGlobal(headerSize); + try + { + Marshal.StructureToPtr(header, headerPtr, false); + Marshal.Copy(headerPtr, payload, 0, headerSize); + } + finally + { + Marshal.FreeHGlobal(headerPtr); + } + + Buffer.BlockCopy(queryStrBytes, 0, payload, headerSize, queryStrBytes.Length); + return payload; + } + + /// + /// Everything から返信された EVERYTHING_IPC_LISTW バイナリをパースし、スナップショットに登録します。 + /// + private static void ParseEverythingIpcList(IntPtr pList, string targetDirectory, FastDirectorySnapshot snapshot) + { + int totitems = Marshal.ReadInt32(pList, 0); + int numitems = Marshal.ReadInt32(pList, 4); + int offset = Marshal.ReadInt32(pList, 8); + + if (numitems <= 0) return; + + int itemHeaderBase = 12; // sizeof(DWORD) * 3 + int itemSize = 12; // sizeof(DWORD) * 3 (flags, filename_offset, path_offset) + + for (int i = 0; i < numitems; i++) + { + int itemOffset = itemHeaderBase + (i * itemSize); + uint flags = (uint)Marshal.ReadInt32(pList, itemOffset); + int filenameOffset = Marshal.ReadInt32(pList, itemOffset + 4); + int pathOffset = Marshal.ReadInt32(pList, itemOffset + 8); + + string filename = Marshal.PtrToStringUni(IntPtr.Add(pList, filenameOffset)) ?? string.Empty; + string dirPath = Marshal.PtrToStringUni(IntPtr.Add(pList, pathOffset)) ?? string.Empty; + + bool isFolder = (flags & EVERYTHING_IPC_FOLDER) != 0 || (flags & EVERYTHING_IPC_DRIVE) != 0; + + if (isFolder) + { + string fullSubDir = Path.Combine(dirPath, filename); + snapshot.AddDirectory(dirPath, fullSubDir); + } + else + { + snapshot.AddFile(dirPath, filename); + } + } + } + #endregion + + #region □P/Invoke(Private) + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + private static extern IntPtr FindWindowW(string lpClassName, string? lpWindowName); + + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, ref COPYDATASTRUCT lParam); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool PeekMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg); + + [DllImport("user32.dll")] + private static extern bool TranslateMessage([In] ref MSG lpMsg); + + [DllImport("user32.dll")] + private static extern IntPtr DispatchMessage([In] ref MSG lpmsg); + #endregion + } +}