如何在Delphi中为变量分配语句?

时间:2019-04-27 20:02:07

标签: delphi

下面的C代码如何在Delphi中完成?我尝试翻译,但似乎Delphi不允许使用此语法。基本上,我需要像在C代码中那样将函数分配给变量。在Delphi上怎么做?

这是参考的C代码:

void EnumWindowsTopToDown(HWND owner, WNDENUMPROC proc, LPARAM param)
{
    HWND currentWindow = GetTopWindow(owner);
    if (currentWindow == NULL)
        return;
    if ((currentWindow = GetWindow(currentWindow, GW_HWNDLAST)) == NULL)
        return;
    while (proc(currentWindow, param) && (currentWindow = GetWindow(currentWindow, GW_HWNDPREV)) != NULL);
}

这是我的尝试:

type
  TFNWndEnumProc = function(_hwnd: HWND; _lParam: LPARAM): BOOL; stdcall;

    procedure EnumWindowsTopToDown(Owner: HWND; Proc: TFNWndEnumProc;
      _Param: LPARAM);
    var
      CurrentWindow: HWND;
    begin
      CurrentWindow := GetTopWindow(Owner);
      if CurrentWindow = 0 then
        Exit;

      CurrentWindow := GetWindow(CurrentWindow, GW_HWNDLAST);
      if CurrentWindow = 0 then
        Exit;

      while Proc(CurrentWindow, _Param) and (CurrentWindow :=  GetWindow(CurrentWindow, GW_HWNDPREV)) <> 0;
    end;

2 个答案:

答案 0 :(得分:5)

Delphi无法像C / C ++一样在whileif语句内分配变量。您需要分解while语句,就像必须在调用if时分解GetWindow(GW_HWNDLAST)语句一样,例如:

type
  TFNWndEnumProc = function(_hwnd: HWND; _lParam: LPARAM): BOOL; stdcall;

procedure EnumWindowsTopToDown(Owner: HWND; Proc: TFNWndEnumProc; Param: LPARAM);
var
  CurrentWindow: HWND;
begin
  CurrentWindow := GetTopWindow(Owner);
  if CurrentWindow = 0 then
    Exit;

  CurrentWindow := GetWindow(CurrentWindow, GW_HWNDLAST);
  if CurrentWindow = 0 then
    Exit;

  while Proc(CurrentWindow, Param) do
  begin
    CurrentWindow := GetWindow(CurrentWindow, GW_HWNDPREV);
    if CurrentWindow = 0 then Exit;
  end;
end;

答案 1 :(得分:2)

在C和C ++中,赋值是表达式,其结果是赋值。这就是为什么您可以采用分配的值的原因:

while ((a = getNextValue()) != 13) 
{
   // code of loop
} 

在Pascal和Delphi中,惊讶只是一个陈述,而不是返回值的东西。因此,您首先必须执行分配并在下一步中查询完成分配的变量:

a := getNextValue;
while (a <> 13) do
begin
  // code of loop;
  a := getNextValue;
end;

Remy的代码很好,但是可以简化一点。我也已经转换了代码,并想到了:

type
  WNDENUMPROC = function(hwnd: HWND; lParam: LPARAM): BOOL stdcall;

procedure EnumWindowsTopToDown(owner: HWND; proc: WNDENUMPROC; param: LPARAM);
var
  currentWindow: HWND;
begin
  currentWindow := GetTopWindow(owner);
  if currentWindow = 0 then
    Exit;
  currentWindow := GetWindow(currentWindow, GW_HWNDLAST);
  while (currentWindow <> 0) and proc(currentWindow, param) do
    currentWindow := GetWindow(currentWindow, GW_HWNDPREV);
end;