Examples Delphi

Title: Processor Usage
Question: How to get the processor usage
Answer:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, CommCtrl, StdCtrls, Menus,WinSpool, ExtCtrls, Buttons, Registry;
type
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
Label2: TLabel;
Timer1: TTimer;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
started : boolean;
reg : TRegistry;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
Dummy : array[0..1024] of byte;
begin
// Stats started by Button1 hit
Reg:=TRegistry.Create;
Reg.RootKey:=HKEY_DYN_DATA; // Statistic data is saved under this topic
{ Before starting retrieving statistic data you have to query
the appropiate key under 'PerfStats\StartStat'. }
Reg.OpenKey('PerfStats\StartStat',false); // Open this key first to start collecting performance data
Reg.ReadBinaryData('KERNEL\CPUUsage',Dummy,Sizeof(Dummy));
Reg.CloseKey;
started:=true;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
CPUU : integer;
begin
{ After starting the collection of statistic data, you can retrieve the
recent value under the 'PerfStats\StatData' key. This is done by a timer
event in this example }
if started then
begin
Reg.OpenKey('PerfStats\StatData',false); // Open extension kex for txt files
Reg.ReadBinaryData('KERNEL\CPUUsage',CPUU,SizeOf(Integer));
Reg.CloseKey;
Label1.Caption:=IntToStr(CPUU)+'%';
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Dummy : array[0..1024] of byte;
begin
// Button2 hit stops statistic collection
{ Collecting statistic data is stopped by a query under 'PerfStats/StopStat' }
Reg.OpenKey('PerfStats\StopStat',false); // Open this key first to start collecting performance data
Reg.ReadBinaryData('KERNEL\CPUUsage',Dummy,SizeOf(Dummy));
Reg.Free;
Started:=false;
end;
end.