如何在Win中捕获应用程序(进程)的开始和完成。 如何衡量每次申请的时间?
答案 0 :(得分:3)
您可以使用GetProcessTimes函数获取特定流程的时间信息。
BOOL WINAPI GetProcessTimes(
__in HANDLE hProcess,
__out LPFILETIME lpCreationTime,
__out LPFILETIME lpExitTime,
__out LPFILETIME lpKernelTime,
__out LPFILETIME lpUserTime
);
参见此示例
program GetProcessTime;
{$APPTYPE CONSOLE}
uses
DateUtils,
Windows,
tlhelp32,
SysUtils;
Procedure GetAllProcessTime;
var
HandleSnapShot : THandle;
EntryParentProc : TProcessEntry32;
DummyCreateFileTime : Windows.FILETIME;
DummyExitFileTime : Windows.FILETIME;
DummyKernelFileTime : Windows.FILETIME;
DummyUserFileTime : Windows.FILETIME;
aFileName : String;
h : THandle;
ActualTime : TDateTime;
Dif : TDateTime;
CreationTime : TDateTime;
function FileTime2DateTime(FileTime: TFileTime): TDateTime; //Convert then FileTime to TDatetime format
var
LocalTime: TFileTime;
DOSTime : Integer;
begin
FileTimeToLocalFileTime(FileTime, LocalTime);
FileTimeToDosDateTime(LocalTime, LongRec(DOSTime).Hi, LongRec(DOSTime).Lo);
Result := FileDateToDateTime(DOSTime);
end;
begin
HandleSnapShot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); //get the list of process
if HandleSnapShot <> INVALID_HANDLE_VALUE then
begin
EntryParentProc.dwSize := SizeOf(EntryParentProc);
if Process32First(HandleSnapShot, EntryParentProc) then //Get the first process in the list
begin
Writeln( Format('%-30s %-20s %-16s',['FileName','Start','Running Time']) );
ActualTime:=Now;
repeat
h:=OpenProcess(PROCESS_QUERY_INFORMATION,false,EntryParentProc.th32ProcessID); //open a particular process
if GetProcessTimes(h, DummyCreateFileTime, DummyExitFileTime, DummyKernelFileTime, DummyUserFileTime) then //get the timing info
begin
aFileName:=ExtractFileName(EntryParentProc.szExeFile);
CreationTime:=FileTime2DateTime(DummyCreateFileTime); //get the initial time of the process
Dif := ActualTime-CreationTime; //calculate the elapsed time
Writeln( Format('%-30s %-20s %-16s',[aFileName,FormatDateTime('DD-MM-YYYY HH:NN:SS',CreationTime),FormatDateTime('HH:NN:SS',Dif)]) );
end;
CloseHandle(h);
until not Process32Next(HandleSnapShot, EntryParentProc);
end;
CloseHandle(HandleSnapShot);
end;
end;
begin
try
GetAllProcessTime();
Readln;
except
on E: Exception do
begin
Writeln(E.ClassName, ': ', E.Message);
Readln;
end;
end;
end.
答案 1 :(得分:2)
在名称中有大约几个带有'hook'的Windows API调用,允许您捕获系统范围的事件。您必须将它们构建到DLL中,然后从单独的应用程序调用“挂钩”DLL。
非常简短,就是这样。希望能让你开始!
答案 2 :(得分:1)
WH_CBT hook很可能是你追求的那个。它允许您在创建或销毁窗口时通知操作系统。您将需要使用此钩子来抓取句柄,并使用句柄使用GetWindowThreadProcessId获取进程ID。然后,您可以将此句柄传递给函数GetProcessTimes(由RRUZ建议)以获取时间。 GpSysHook来源中提供了一个示例(虽然已过时,概念仍然相同)。
答案 3 :(得分:1)
Windows Performance Analyzer具有专门用于计时应用程序的功能,即使它们处于启动或登录顺序。
答案 4 :(得分:1)
Windows Management Instrumentation提供事件订阅。 WMI的优点在于它使用DCOM和SOAP也可以远程工作。
WMI offers the capability to notify a subscriber for any event it is interested in.
WMI使用WMI查询语言(WQL) 提交WQL事件查询和 定义事件的类型 回。事件机制,与 所有相关的回调,都是其中的一部分 WMI COM / DCOM和自动化 接口
Delphi的免费WMI客户端实现可在线获取(不确定它是否支持事件回调):