public static GetExcelProcessId ( ) : uint | ||
Результат | uint |
public WinEventHook(WinEventDelegate handler, WinEvent eventMin, WinEvent eventMax, string xllPath) { // Note : could we use another handle than one of an xll ? // Thus we could avoid carrying the xll path. // The events are still hooked after the xll has been unloaded. var xllModuleHandle = Win32Helper.GetModuleHandle(xllPath); var excelProcessId = Win32Helper.GetExcelProcessId(); _procDelegate = handler; _hWinEventHook = SetWinEventHook(eventMin, eventMax, xllModuleHandle, handler, excelProcessId, 0, SetWinEventHookFlags.WINEVENT_INCONTEXT); }
// Must run on the main Excel thread (or another thread where Windows messages are pumped) void InstallWinEventHook(object _) { var excelProcessId = Win32Helper.GetExcelProcessId(); _hWinEventHook = SetWinEventHook(_eventMin, _eventMax, IntPtr.Zero, _handleWinEventDelegate, excelProcessId, 0, SetWinEventHookFlags.WINEVENT_OUTOFCONTEXT); if (_hWinEventHook == IntPtr.Zero) { Logger.WinEvents.Error("SetWinEventHook failed"); // Is SetLastError used? - SetWinEventHook documentation does not indicate so throw new Win32Exception("SetWinEventHook failed"); } Logger.WinEvents.Info($"SetWinEventHook success on thread {Thread.CurrentThread.ManagedThreadId}"); }
readonly WinEventDelegate _handleWinEventDelegate; // Ensures delegate that we pass to SetWinEventHook is not GC'd public WinEventHook(WinEvent eventMin, WinEvent eventMax, SynchronizationContext syncContextAuto, IntPtr hWndFilterOrZero) { if (syncContextAuto == null) { throw new ArgumentNullException(nameof(syncContextAuto)); } _syncContextAuto = syncContextAuto; _hWndFilterOrZero = hWndFilterOrZero; var xllModuleHandle = Win32Helper.GetXllModuleHandle(); var excelProcessId = Win32Helper.GetExcelProcessId(); _handleWinEventDelegate = HandleWinEvent; _hWinEventHook = SetWinEventHook(eventMin, eventMax, xllModuleHandle, _handleWinEventDelegate, excelProcessId, 0, SetWinEventHookFlags.WINEVENT_INCONTEXT); if (_hWinEventHook == IntPtr.Zero) { Logger.WinEvents.Error("SetWinEventHook failed"); // Is SetLastError used? - SetWinEventHook documentation does not indicate so throw new Win32Exception("SetWinEventHook failed"); } Logger.WinEvents.Info($"SetWinEventHook success on thread {Thread.CurrentThread.ManagedThreadId}"); }