How to pass the address of a thread function as a winapi callback?

I have a simple thread, and inside the execution I'm trying to call EnumWindows () with the address of one of the functions defined in the thread. So I'm trying to do this: EnumWindows (@cbEnumWindowsClickOK, 0); where cbEnumWindowsClickOK is the EnumWindowProc defined inside the stream class, for example:

TAutoClickOKThread = class(TThread) private fExitEvent : THandle; function cbEnumWindowsClickOK(Wnd: HWND; Info: Pointer): BOOL; public constructor Create(ExitEvent : Thandle); procedure Execute(); override; end; 

When I try to do this, I keep getting "Error: Variable required", hinting that it does not interpret @cbEnumWindowsClickOK as an address. If I transfer this function to the global scope (removing it from the stream), it works.

Any thoughts on how I can fix this?

+1
source share
1 answer

You need to pass EnumWindows simple old function, that is, one that is not bound to an instance. You must transfer the instance separately. Like this:

 function EnumFunc(hwnd: HWND; lParam: LPARAM): BOOL; stdcall; begin Result := TAutoClickOKThread(lParam).cbEnumWindowsClickOK(hwnd); //note that there is now no need for the Info parameter end; ... procedure TAutoClickOKThread.Execute; begin ... EnumWindows(EnumFunc, LPARAM(Self)); ... end; 

The reason this should be done is because the instance method does not match the required signature for EnumWindows . The instance has an additional, implicit parameter containing a reference to the instance, i.e. Self . Here's how you can access instance members. But the signature for EnumFunc not suitable for this.

+6
source

Source: https://habr.com/ru/post/1396216/


All Articles