如何调用EnumWindowsProc? [英] How do I call EnumWindowsProc?
本文介绍了如何调用EnumWindowsProc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试列出我计算机上正在运行的所有进程。
我的简短示例代码中的EnumWindowsProc()
调用语句有什么问题。我的编译器声明,在这一行中:
EnumWindows(@EnumWindowsProc, ListBox1);
函数调用中需要有一个变量。我应该如何将@EnumWindowsProc
更改为变量?
unit Unit_process_logger;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.StdCtrls;
type
TForm1 = class(TForm)
ListBox1: TListBox;
Timer1: TTimer;
procedure Timer1Timer(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
function EnumWindowsProc(wHandle: HWND; lb: TListBox): Boolean;
var
Form1: TForm1;
implementation
{$R *.dfm}
function EnumWindowsProc(wHandle: HWND; lb: TListBox): Boolean;
var
Title, ClassName: array[0..255] of Char;
begin
GetWindowText(wHandle, Title, 255);
GetClassName(wHandle, ClassName, 255);
if IsWindowVisible(wHandle) then
lb.Items.Add(string(Title) + '-' + string(ClassName));
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
ListBox1.Items.Clear;
EnumWindows(@EnumWindowsProc, ListBox1);
end;
end.
推荐答案
首先声明是错误的。它需要stdcall
,并返回BOOL
。
function EnumWindowsProc(wHandle: HWND; lb: TListBox): BOOL; stdcall;
其次,您的实现没有设置返回值。返回True
继续枚举,返回False
停止枚举。在您的情况下,需要返回True
。
最后,您需要在调用EnumWindows
时将列表框强制转换为LPARAM
。
EnumWindows(@EnumWindowsProc , LPARAM(ListBox1));
有关完整的详细信息,请参阅documentation。
把所有这些放在一起,你就得到了这个:
function EnumWindowsProc(wHandle: HWND; lb: TListBox): BOOL; stdcall;
var
Title, ClassName: array[0..255] of char;
begin
GetWindowText(wHandle, Title, 255);
GetClassName(wHandle, ClassName, 255);
if IsWindowVisible(wHandle) then
lb.Items.Add(string(Title) + '-' + string(ClassName));
Result := True;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
ListBox1.Items.Clear;
EnumWindows(@EnumWindowsProc, LPARAM(ListBox1));
end;
还请注意,EnumWindows
不会列举所有正在运行的进程。它所做的是枚举所有顶级窗口。请注意完全相同的事情。要枚举所有正在运行的进程,有EnumProcesses
。但是,由于您正在读出窗口标题和窗口类名,因此您可能确实希望使用EnumWindows
。
正如我以前多次说过的,我不喜欢
EnumWindows
的Delphi头转换使用Pointer
作为EnumWindowsProc
参数。这意味着您不能依赖编译器来检查类型安全。我个人总是使用我自己的EnumWindows
版本。
type
TFNWndEnumProc = function(hwnd: HWND; lParam: LPARAM): BOOL; stdcall;
function EnumWindows(lpEnumFunc: TFNWndEnumProc; lParam: LPARAM): BOOL;
stdcall; external user32;
然后,当您调用函数时,您不使用@
运算符,因此让编译器检查您的回调函数是否正确声明:
EnumWindows(EnumWindowsProc, ...);
这篇关于如何调用EnumWindowsProc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文