SetWinEventHook와 같은 파라미터에 콜백 함수를 받는 Winapi P/Invoke 함수가 작동되지 않는 문제가 있습니다.
(SetWinEventHook 함수 설명 : SetWinEventHook function (winuser.h) - Win32 apps | Microsoft Learn)
생성자와 같은 메소드 안에 SetWinEventHook 메소드를 집어넣을 때는 원할 때 마다 콜백 함수가 제대로 작동하는 데
그 외 일반 코드에서는 작동되지 않는데 이걸 어떻게 해결할 수 있는지 해메고 있습니다.
[DllImport("user32.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc,
[MarshalAs(UnmanagedType.FunctionPtr)] WinEventDelegate lpfnWinEventProc, int idProcess, int idThread, WinEventFlags dwFlags);
// import 한 P/Invoke 함수
public void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
}
// 실행되야하는 콜백 함수
public MyApp()
{
var MFCLibGridCtrl = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "MFCLibGridCtrl"));
var MFCLibProcess = Process.GetProcessById(MFCLibGridCtrl.Current.ProcessId);
WindowControlService.WinEventDelegate winEventDelegate = new WindowControlService.WinEventDelegate(WinEventProc);
GCHandle.Alloc(winEventDelegate);
WindowControlService.SetWinEventHook(
0x7, 0x8,
IntPtr.Zero,
winEventDelegate,
MFCLibProcess.Id, 0,
WindowControlService.WinEventFlags.WINEVENT_OUTOFCONTEXT);
}
// 생성자에서는 콜백 함수를 제대로 불러옴
ILogic iLogic = new Logic();
iLogic.Execute();
public async Task Execute()
{
var MFCLibGridCtrl = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "MFCLibGridCtrl"));
var MFCLibProcess = Process.GetProcessById(MFCLibGridCtrl.Current.ProcessId);
WindowControlService.WinEventDelegate winEventDelegate = new WindowControlService.WinEventDelegate(WinEventProc);
GCHandle.Alloc(winEventDelegate);
WindowControlService.SetWinEventHook(
0x7, 0x8,
IntPtr.Zero,
winEventDelegate,
MFCLibProcess.Id, 0,
WindowControlService.WinEventFlags.WINEVENT_OUTOFCONTEXT);
}
// 여기서는 제대로 콜백 함수가 작동되지 않음