如何将方法作为回调传递给Windows API调用? [英] How to pass a method as callback to a Windows API call?

查看:103
本文介绍了如何将方法作为回调传递给Windows API调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递一个类的方法作为回调到WinAPI函数。这是可能的,如果是,如何?

I'd like to pass a method of a class as callback to a WinAPI function. Is this possible and if yes, how?

设置计时器的示例:

TMyClass = class
public
  procedure TimerProc(Wnd:HWND; uMsg:DWORD; idEvent:PDWORD; dwTime:DWORD);
  procedure DoIt;
end;
[...]
procedure TMyClass.DoIt;
begin
  SetTimer(0, 0, 8, @TimerProc);  // <-???- that's what I want to do (last param)
end;

感谢您的帮助!

编辑:目标是将此类的方法指定为回调。

Edit: The goal is to specify a method of this class as callback. No procedure outside the class.

Edit2 :感谢您的帮助,但只要该方法没有TMyClass。在它的名字前面,这不是我正在寻找的。我以前这样做,但想知道是否可以完全保持在面向对象的世界。指针魔术欢迎。

Edit2: I appreciate all your help but as long as the method has no "TMyClass." in front of its name it is not what I am searching for. I used to do it this way but wondered if could stay fully in the object oriented world. Pointer magic welcome.

推荐答案

Madshi 具有 MethodToProcedure 过程。它在madTools.pas中,它在madBasic包中。如果你使用它,你应该将调用约定的TimerProc更改为stdcall,并且DoIt过程将变为

Madshi has a MethodToProcedure procedure. It's in the "madTools.pas" which is in the "madBasic" package. If you use it, you should change the calling convention for "TimerProc" to stdcall and DoIt procedure would become,

TMyClass = class
private
  Timer: UINT;
  SetTimerProc: Pointer;
[...]

procedure TMyClass.DoIt;
begin
  SetTimerProc := MethodToProcedure(Self, @TMyClass.TimerProc);
  Timer := SetTimer(0, 0, 8, SetTimerProc);
end;
// After "KillTimer(0, Timer)" is called call:
// VirtualFree(SetTimerProc, 0, MEM_RELEASE);



我从来没有尝试过,但我想也可以尝试复制classses.MakeObjectInstance中的代码用于传递其他过程类型,而不是TWndMethod。


I've never tried but I think one could also try to duplicate the code in the "classses.MakeObjectInstance" for passing other procedure types than TWndMethod.

这篇关于如何将方法作为回调传递给Windows API调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆