2004. március 24., szerda
How to get the process ID's of all running programs
Problem/Question/Abstract:
I am trying to build a component to get info about the programs executing in my NT4 environment. I managed to get the names for all the windows running (title text). Now, how can I get the process ID for each of them? Which function should I use? Is there any function that tells me for how long my process is running?
Answer:
It is better to use the EnumWindows function instead of FindWindow/GetWindow, because the latter isn't sensitive to windows being destroyed halfway through the loop and you can end up getting invalid handles. Here's an example:
function EnumWindowsProc(hWnd: LongWord; Form: TForm1): WordBool; stdcall;
begin
Form.FoundAWindow(hWnd);
Result := True
end;
procedure TForm1.FoundAWindow(hWnd: LongWord);
var
ProcessID: LongWord;
Title: array[0..255] of Char;
begin
GetWindowThreadProcessID(hWnd, @ProcessID);
GetWindowText(hWnd, Title, 256);
{Now, do whatever you want with Title and ProcessID, e.g.:}
Memo1.Lines.Add(Title + ' [' + IntToStr(ProcessID) + ']')
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
EnumWindows(@EnumWindowsProc, Integer(Self))
end;
2004. március 23., kedd
Retrieve version information from an executable or DLL
Problem/Question/Abstract:
Is there a quick way to include the build number created by Project/ Options/ Version Info in my About Box?
Answer:
Solve 1:
Here's a function which will read the version info:
{Get Major, Minor, Release, Build for an EXE or DLL file.
returns true = success.
returns false = failure, probably info not found in the file.}
function GetFileVersion(const FileName: string; var Major, Minor, Release, Build:
Integer;
var PreRelease, Debug: Boolean; var Description: string): Boolean;
var
Zero: DWORD; {set to 0 by GetFileVersionInfoSize}
VersionInfoSize: DWORD;
PVersionData: pointer;
PFixedFileInfo: PVSFixedFileInfo;
FixedFileInfoLength: UINT;
FileFlags: WORD;
begin
{ask Windows how big a data buffer to allocate to hold this EXE or DLL version info}
VersionInfoSize := GetFileVersionInfoSize(pChar(FileName), Zero);
{if no version info in the EXE or DLL}
if VersionInfoSize = 0 then
begin
result := False;
exit;
end;
{allocate memory needed to hold version info}
PVersionData := AllocMem(VersionInfoSize);
try
{load version resource out of EXE or DLL into our buffer}
if GetFileVersionInfo(pChar(FileName), 0, VersionInfoSize, PVersionData) = false
then
begin
raise Exception.Create('Can''''t get version info');
end;
{get the fixed file info portion of the resource in buffer}
if VerQueryValue(PVersionData, '\', pointer(PFixedFileInfo), FixedFileInfoLength)
= false then
begin
{no fixed file info in this version resource !}
result := False;
exit;
end;
{extract the info from the the fixed file data structure}
Major := PFixedFileInfo^.dwFileVersionMS shr 16;
Minor := PFixedFileInfo^.dwFileVersionMS and $FFFF;
Release := PFixedFileInfo^.dwFileVersionLS shr 16;
Build := PFixedFileInfo^.dwFileVersionLS and $FFFF;
FileFlags := PFixedFileInfo^.dwFileFlags;
PreRelease := (VS_FF_PRERELEASE and FileFlags) < > 0;
Debug := (VS_FF_DEBUG and FileFlags) < > 0;
Description := Format('Ver %d.%d, Release %d Build %d', [Major, Minor, Release,
Build]);
if PreRelease then
begin
Description := Description + ' Beta';
end;
if Debug then
begin
Description := Description + ' Debug';
end;
finally
FreeMem(PVersionData);
end;
result := True;
end;
Solve 2:
{ ... }
TVer = record
case integer of
0: (both: integer);
1: (LowPart, HighPart: Word);
end;
TVersion = record
Major: Word;
Minor: Word;
Release: Word;
Build: Word;
end;
function GetVersionInfo(FileName: string): TVersion;
var
Len: DWord;
Size: DWord;
buf: pChar;
Info: pVSFixedFileInfo;
begin
fillChar(result, sizeOf(TVersion), #0);
Size := GetFileVersionInfoSize(pChar(FileName), Len);
if Size = 0 then
exit;
GetMem(buf, Size);
try
GetFileVersionInfo(pChar(FileName), 0, Size, buf);
if VerQueryValue(buf, '\', pointer(Info), Len) then
with Result do
begin
Major := TVer(Info.dwFileVersionMS).HighPart;
Minor := TVer(Info.dwFileVersionMS).LowPart;
Release := TVer(Info.dwFileVersionLS).HighPart;
Build := TVer(Info.dwFileVersionLS).LowPart;
end;
finally
FreeMem(buf);
end;
end;
Solve 3:
Get the version info stored inside a DLL.
function dgGetBuildInfo: string;
var
V1, V2, V3, V4: Word;
VerInfoSize: DWORD;
VerInfo: Pointer;
VerValueSize: DWORD;
VerValue: PVSFixedFileInfo;
Dummy: DWORD;
begin
VerInfoSize := GetFileVersionInfoSize(PChar(ParamStr(0)), Dummy);
GetMem(VerInfo, VerInfoSize);
try
GetFileVersionInfo(PChar(ParamStr(0)), 0, VerInfoSize, VerInfo);
VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize);
with VerValue^ do
begin
V1 := dwFileVersionMS shr 16;
V2 := dwFileVersionMS and $FFFF;
V3 := dwFileVersionLS shr 16;
V4 := dwFileVersionLS and $FFFF;
end;
Result := IntToStr(V1) + '.' + IntToStr(V2) + '.' + IntToStr(V3) + '.' +
IntToStr(V4);
finally
FreeMem(VerInfo, VerInfoSize);
end;
end;
2004. március 22., hétfő
How to generate coherent noise
Problem/Question/Abstract:
How to generate coherent noise
Answer:
{Coherent noise function over 1, 2 or 3 dimensions by Ken Perlin}
unit perlin;
interface
function noise1(arg: double): double;
function noise2(vec0, vec1: double): double;
function noise3(vec0, vec1, vec2: double): double;
function PNoise1(x, alpha, beta: double; n: integer): double;
function PNoise2(x, y, alpha, beta: double; n: integer): double;
function PNoise3(x, y, z, alpha, beta: double; n: integer): double;
{High Alpha: smoother intensity change, lower contrast
Low Alpha: rapid intensity change, higher contrast
High Beta: coarse, big spots
Low Beta: fine, small spots}
implementation
uses
SysUtils;
const
defB = $100;
defBM = $FF;
defN = $1000;
var
start: boolean = true;
p: array[0..defB + defB + 2 - 1] of integer;
g3: array[0..defB + defB + 2 - 1, 0..2] of double;
g2: array[0..defB + defB + 2 - 1, 0..1] of double;
g1: array[0..defB + defB + 2 - 1] of double;
function s_curve(t: double): double;
begin
result := t * t * (3.0 - 2.0 * t);
end;
function lerp(t, a, b: double): double;
begin
result := a + t * (b - a);
end;
procedure setup(veci: double; var b0, b1: integer; var r0, r1: double);
var
t: double;
begin
t := veci + defN;
b0 := trunc(t) and defBM;
b1 := (b0 + 1) and defBM;
r0 := t - int(t);
r1 := r0 - 1.0;
end;
procedure normalize2(var v0, v1: double);
var
s: double;
begin
s := sqrt(v0 * v0 + v1 * v1);
v0 := v0 / s;
v1 := v1 / s;
end;
procedure normalize3(var v0, v1, v2: double);
var
s: double;
begin
s := sqrt(v0 * v0 + v1 * v1 + v2 * v2);
v0 := v0 / s;
v1 := v1 / s;
v2 := v2 / s;
end;
procedure init;
var
i, j, k: integer;
begin
for i := 0 to defB - 1 do
begin
p[i] := i;
g1[i] := (random(defB + defB) - defB) / defB;
for j := 0 to 1 do
g2[i, j] := (random(defB + defB) - defB) / defB;
normalize2(g2[i, 0], g2[i, 1]);
for j := 0 to 2 do
g3[i, j] := (random(defB + defB) - defB) / defB;
normalize3(g3[i, 0], g3[i, 1], g3[i, 2]);
end;
i := defB;
while i > 0 do
begin
k := p[i];
j := random(defB);
p[i] := p[j];
p[j] := k;
dec(i);
end;
for i := 0 to defB + 1 do
begin
p[defB + i] := p[i];
g1[defB + i] := g1[i];
for j := 0 to 1 do
g2[defB + i, j] := g2[i, j];
for j := 0 to 2 do
g3[defB + i, j] := g3[i, j];
end;
end;
function noise1(arg: double): double;
var
bx0, bx1: integer;
rx0, rx1, sx, u, v: double;
begin
if start then
begin
init;
start := false;
end;
bx0 := trunc(arg + defN) and defBM;
bx1 := (bx0 + 1) and defBM;
rx0 := frac(arg + defN);
rx1 := rx0 - 1.0;
sx := rx0 * rx0 * (3.0 - 2.0 * rx0);
u := rx0 * g1[p[bx0]];
v := rx1 * g1[p[bx1]];
result := u + sx * (v - u);
end;
function noise2(vec0, vec1: double): double;
var
i, j, bx0, bx1, by0, by1, b00, b10, b01, b11: integer;
rx0, rx1, ry0, ry1, sx, sy, a, b, u, v: double;
begin
if start then
begin
init;
start := false;
end;
bx0 := trunc(vec0 + defN) and defBM;
bx1 := (bx0 + 1) and defBM;
rx0 := frac(vec0 + defN);
rx1 := rx0 - 1.0;
by0 := trunc(vec1 + defN) and defBM;
by1 := (by0 + 1) and defBM;
ry0 := frac(vec1 + defN);
ry1 := ry0 - 1.0;
i := p[bx0];
j := p[bx1];
b00 := p[i + by0];
b10 := p[j + by0];
b01 := p[i + by1];
b11 := p[j + by1];
sx := rx0 * rx0 * (3.0 - 2.0 * rx0);
sy := ry0 * ry0 * (3.0 - 2.0 * ry0);
u := rx0 * g2[b00, 0] + ry0 * g2[b00, 1];
v := rx1 * g2[b10, 0] + ry0 * g2[b10, 1];
a := u + sx * (v - u);
u := rx0 * g2[b01, 0] + ry1 * g2[b01, 1];
v := rx1 * g2[b11, 0] + ry1 * g2[b11, 1];
b := u + sx * (v - u);
result := a + sy * (b - a);
end;
function noise3orig(vec0, vec1, vec2: double): double;
var
i, j, bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11: integer;
rx0, rx1, ry0, ry1, rz0, rz1, sx, sy, sz, a, b, c, d, u, v: double;
begin
if start then
begin
start := false;
init;
end;
setup(vec0, bx0, bx1, rx0, rx1);
setup(vec1, by0, by1, ry0, ry1);
setup(vec2, bz0, bz1, rz0, rz1);
i := p[bx0];
j := p[bx1];
b00 := p[i + by0];
b10 := p[j + by0];
b01 := p[i + by1];
b11 := p[j + by1];
sx := s_curve(rx0);
sy := s_curve(ry0);
sz := s_curve(rz0);
u := rx0 * g3[b00 + bz0, 0] + ry0 * g3[b00 + bz0, 1] + rz0 * g3[b00 + bz0, 2];
v := rx1 * g3[b10 + bz0, 0] + ry0 * g3[b10 + bz0, 1] + rz0 * g3[b10 + bz0, 2];
a := lerp(sx, u, v);
u := rx0 * g3[b01 + bz0, 0] + ry1 * g3[b01 + bz0, 1] + rz0 * g3[b01 + bz0, 2];
v := rx1 * g3[b11 + bz0, 0] + ry1 * g3[b11 + bz0, 1] + rz0 * g3[b11 + bz0, 2];
b := lerp(sx, u, v);
c := lerp(sy, a, b);
u := rx0 * g3[b00 + bz1, 0] + ry0 * g3[b00 + bz1, 1] + rz1 * g3[b00 + bz1, 2];
v := rx1 * g3[b10 + bz1, 0] + ry0 * g3[b10 + bz1, 1] + rz1 * g3[b10 + bz1, 2];
a := lerp(sx, u, v);
u := rx0 * g3[b01 + bz1, 0] + ry1 * g3[b01 + bz1, 1] + rz1 * g3[b01 + bz1, 2];
v := rx1 * g3[b11 + bz1, 0] + ry1 * g3[b11 + bz1, 1] + rz1 * g3[b11 + bz1, 2];
b := lerp(sx, u, v);
d := lerp(sy, a, b);
result := lerp(sz, c, d);
end;
function noise3(vec0, vec1, vec2: double): double;
var
i, j, bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11: integer;
rx0, rx1, ry0, ry1, rz0, rz1, sx, sy, sz, a, b, c, d, u, v: double;
begin
if start then
begin
start := false;
init;
end;
bx0 := trunc(vec0 + defN) and defBM;
bx1 := (bx0 + 1) and defBM;
rx0 := frac(vec0 + defN);
rx1 := rx0 - 1.0;
by0 := trunc(vec1 + defN) and defBM;
by1 := (by0 + 1) and defBM;
ry0 := frac(vec1 + defN);
ry1 := ry0 - 1.0;
bz0 := trunc(vec2 + defN) and defBM;
bz1 := (bz0 + 1) and defBM;
rz0 := frac(vec2 + defN);
rz1 := rz0 - 1.0;
i := p[bx0];
j := p[bx1];
b00 := p[i + by0];
b10 := p[j + by0];
b01 := p[i + by1];
b11 := p[j + by1];
sx := rx0 * rx0 * (3.0 - 2.0 * rx0);
sy := ry0 * ry0 * (3.0 - 2.0 * ry0);
sz := rz0 * rz0 * (3.0 - 2.0 * rz0);
u := rx0 * g3[b00 + bz0, 0] + ry0 * g3[b00 + bz0, 1] + rz0 * g3[b00 + bz0, 2];
v := rx1 * g3[b10 + bz0, 0] + ry0 * g3[b10 + bz0, 1] + rz0 * g3[b10 + bz0, 2];
a := u + sx * (v - u);
u := rx0 * g3[b01 + bz0, 0] + ry1 * g3[b01 + bz0, 1] + rz0 * g3[b01 + bz0, 2];
v := rx1 * g3[b11 + bz0, 0] + ry1 * g3[b11 + bz0, 1] + rz0 * g3[b11 + bz0, 2];
b := u + sx * (v - u);
c := a + sy * (b - a);
u := rx0 * g3[b00 + bz1, 0] + ry0 * g3[b00 + bz1, 1] + rz1 * g3[b00 + bz1, 2];
v := rx1 * g3[b10 + bz1, 0] + ry0 * g3[b10 + bz1, 1] + rz1 * g3[b10 + bz1, 2];
a := u + sx * (v - u);
u := rx0 * g3[b01 + bz1, 0] + ry1 * g3[b01 + bz1, 1] + rz1 * g3[b01 + bz1, 2];
v := rx1 * g3[b11 + bz1, 0] + ry1 * g3[b11 + bz1, 1] + rz1 * g3[b11 + bz1, 2];
b := u + sx * (v - u);
d := a + sy * (b - a);
result := c + sz * (d - c);
end;
{Harmonic summing functions}
{In what follows "alpha" is the weight when the sum is formed. Typically it is 2. As this
approaches 1 the function is noisier.
"beta" is the harmonic scaling/spacing, typically 2.
persistance = 1/alpha
beta = frequency
N = octaves}
function PNoise1(x, alpha, beta: double; n: integer): double;
var
i: integer;
val, sum, p, scale: double;
begin
sum := 0;
scale := 1;
p := x;
for i := 0 to n - 1 do
begin
val := noise1(p);
sum := sum + val / scale;
scale := scale * alpha;
p := p * beta;
end;
result := sum;
end;
function PNoise2(x, y, alpha, beta: double; n: integer): double;
var
i: integer;
val, sum, px, py, scale: double;
begin
sum := 0;
scale := 1;
px := x;
py := y;
for i := 0 to n - 1 do
begin
val := noise2(px, py);
sum := sum + val / scale;
scale := scale * alpha;
px := px * beta;
py := py * beta;
end;
result := sum;
end;
function PNoise3(x, y, z, alpha, beta: double; n: integer): double;
var
i: integer;
val, sum, px, py, pz, scale: double;
begin
sum := 0;
scale := 1;
px := x;
py := y;
pz := z;
for i := 0 to n - 1 do
begin
val := noise3(px, py, pz);
sum := sum + val / scale;
scale := scale * alpha;
px := px * beta;
py := py * beta;
pz := pz * beta;
end;
result := sum;
end;
end.
Used like this:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
Image1: TImage;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
perlin;
procedure TForm1.Button1Click(Sender: TObject);
var
x, y, z, c: integer;
begin
image1.Canvas.Brush.Color := 0;
image1.Canvas.FillRect(image1.Canvas.ClipRect);
for x := 0 to 511 do
for y := 0 to 511 do
begin
z := trunc(pnoise2(x / 100, y / 100, 2, 2, 10) * 128) + 128;
c := z + (z shl 8) + (z shl 16);
image1.Canvas.Pixels[x, y] := c;
end;
c := 0;
repeat
image1.Canvas.Pixels[519, c] := $FFFFFF;
c := c + 10;
until
c > 510;
end;
end.
2004. március 21., vasárnap
How to extract a string from the middle of a sentence
Problem/Question/Abstract:
I need to extract a string from the middle of a sentence. For example: An email will come in with the following subject: Order from the Web : a.dyble@ntlworld.com. My method is to start at the @ sign and work outwards using copy.
Answer:
Solve 1:
This may not be the most efficient, but
function MyWord(const Token: Char; const S: string): string;
var
B, M, E: Integer;
K: string;
begin
Result := '';
M := Pos(Token, S);
if M > 0 then
begin
K := ' ' + S + ' '; {wrap in spaces cause I'm lazy}
B := M + 1;
repeat
Dec(B);
until
K[B] in [' ', #9, #10];
E := M;
repeat
Inc(E);
until
K[E] in [' ', #9, #13];
Result := Copy(S, B, E - B - 1);
end;
end;
Example of using:
procedure TForm1.Button1Click(Sender: TObject);
begin
Caption := MyWord('@', Memo1.Text);
end;
Solve 2:
{Parse item}
procedure ParseItem(var Source, Item: string; Delimiter: Char);
var
CurrentPosition: Integer;
begin
CurrentPosition := Pos(Delimiter, Source);
if CurrentPosition = 0 then
begin
{No delimeter - item is the remaining string}
Item := Source;
Source := '';
end
else
begin
{There is a delimeter}
Item := Copy(Source, 1, CurrentPosition - 1);
Delete(Source, 1, CurrentPosition);
end;
end;
function GetEmailAddress(ASource: string): string;
var
AWord: string;
begin
Result := '';
while ASource <> '' do
begin
ParseItem(ASource, AWord, ' ');
if Pos('@', AWord) <> 0 then
begin
Result := AWord;
Break;
end;
end;
end;
procedure TForm1.Button30Click(Sender: TObject);
begin
ShowMessage(GetEmailAddress('Order from theWeb : a.dyble@ntlworld.com'));
end;
Solve 3:
Can we assume that you always have the colon / blank sequence? If so then this may be easier:
P := Pos(':', Subject) + 2; {Position following the colon / blank}
{Grab everything after}
EMailAddress := Copy(Subject, P, Length(Subject) - P - 1);
Solve 4:
If you can't count on the ' :' as Kurt suggests, perhaps the following will do:
function ExtractEMailAddress(const s: string): string;
const
goodEMailChars = ['A'..'Z', 'a'..'z', '@', '.', '_', '-'];
var
i, j, lth: integer;
begin
i := pos('@', s);
if i > 0 then
begin
j := i + 1;
while (i > 0) and (s[i] in goodEMailChars) do
dec(i);
inc(i);
lth := Length(s);
while (j <= lth) and (s[j] in goodEMailChars) do
inc(j);
result := Copy(s, i, j - i);
end
else
result := '';
end;
Solve 5:
You can use Pos to locate the substrings and Copy to copy the text to a new string. Something like:
function FindSubString(const S, Prefix, Suffix: string): string;
var
P: Integer;
begin
Result := EmptyStr;
P := Pos(Prefix, S);
if P > 0 then
begin
Result := Copy(S, P + Length(Prefix), Length(S));
P := Pos(Suffix, Result);
if P > 0 then
SetLength(Result, P - 1)
else
Result := EmptyStr;
end;
end;
The code isn't very efficient, but it should get you started.
2004. március 20., szombat
Retrieve the computer name
Problem/Question/Abstract:
How to retrieve the computer name
Answer:
Solve 1:
function ComputerName: string;
var
size: DWORD;
begin
size := MAX_COMPUTERNAME_LENGTH + 1;
SetLength(Result, size - 1);
if not GetComputerName(PChar(Result), size) then
Result := '';
end;
Solve 2:
uses
Windows;
procedure GetPCName(var PCName: string);
var
nSize: DWORD;
begin
nSize := MAX_COMPUTERNAME_LENGTH + 1;
PCName := '';
SetLength(PCName, nSize);
if GetComputerName(PChar(PCName), nSize) then
SetLength(PCName, nSize);
end;
Solve 3:
function GetLocalComputerName: string;
var
iLen: cardinal;
begin
iLen := 255;
SetLength(Result, iLen + 1);
if (GetComputerName(PChar(Result), iLen) = false) then
begin
RaiseLastWin32Error;
end;
SetLength(Result, iLen);
end;
2004. március 19., péntek
Change the position of a list item in a TListView (4)
Problem/Question/Abstract:
I want to keep one row as the topmost visible row in a TListView. Each time it will vary according to my search, which one I found I want to make that one as a topmost row. How can I do this?
Answer:
Scroll a listview item to the top:
procedure ScrollItemtoTop(lv: TLIstview; index: Integer);
var
num: Integer;
scrollcode: Integer;
begin
num := lv.TopItem.Index - index;
if num < 0 then
begin
scrollcode := SB_LINEDOWN;
num := Abs(num);
end
else
scrollcode := SB_LINEUP;
lv.Items.BeginUpdate;
try
while num > 0 do
begin
lv.Perform(WM_VSCROLL, scrollcode, 0);
Dec(num);
end;
lv.Perform(WM_VSCROLL, SB_ENDSCROLL, 0);
finally
lv.Items.EndUpdate;
end;
end;
2004. március 18., csütörtök
How to determine file and tree sizes larger 2 GB
Problem/Question/Abstract:
How to determine file and tree sizes larger 2 GB
Answer:
Solve 1:
You will need to use the FindFirstFile, FindNextFile and FindClose functions, e.g.:
function GetFileSize(const FileName: string): Int64;
var
F: TWin32FindData;
H: THandle;
begin
H := FindFirstFile(PChar(FileName), F);
if H = INVALID_HANDLE_VALUE then
RaiseLastWin32Error;
try
Result := F.nFileSizeHigh shl 32 + F.nFileSizeLow;
finally
Windows.FindClose(H);
end;
end;
function GetTreeSize(FileName: string): Int64;
procedure TreeSize(const FileName: string);
var
F: TWin32FindData;
H: THandle;
begin
H := FindFirstFile(PChar(FileName), F);
if H = INVALID_HANDLE_VALUE then
RaiseLastWin32Error;
try
repeat
if ((F.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) > 0) and (F.cFileName[0]
<> '.') then
TreeSize(ExtractFilePath(FileName) + F.cFileName + '\*.*')
else
Result := Result + F.nFileSizeHigh shl 32 + F.nFileSizeLow;
until not FindNextFile(H, F);
finally
Windows.FindClose(H);
end;
end;
begin
Result := 0;
TreeSize(IncludeTrailingBackslash(ExtractFilePath(FileName)) + '*.*');
end;
I would add one little detail to your function. By calculating the filesize, you should cast the values to Int64. In the helpfile you can read, that this is necessary, because the operation would normally return an integer. In this case, (F.nFileSizeHigh shl 32) would return an Integer and not an Int64.
Result := Int64(F.nFileSizeHigh) shl 32 + Int64(F.nFileSizeLow);
I think, casting "nFileSizeLow" is not necessary, but better to make it safe.
Solve 2:
Use the WinAPI version of the function GetFileSize() as follows:
procedure CardinalsToI64(var I: Int64; const LowPart, HighPart: Cardinal);
begin
TULargeInteger(I).LowPart := LowPart;
TULargeInteger(I).HighPart := HighPart;
end;
{ ... }
var
fLOdword: dword;
fHIdword: dword;
FFilesize: Int64;
FFileHandle: THandle;
begin
FFileHandle := CreateFile(PChar(FFileName), GENERIC_READ, FILE_SHARE_READ, nil,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
fLOdword := GetFileSize(FFileHandle, @fHIdword);
CardinalsToI64(FFilesize, fLOdword, fHIdword);
2004. március 17., szerda
Simultaneous 16- and 32bit-Development
Problem/Question/Abstract:
Simultaneous 16- and 32bit-Development
Answer:
If you need to develop 16bit- and 32bit-versions of the same program simultaneously, you just have to consider the following:
Delphi 1 DFM files can be read by Delphi 2 and 3, but not vice versa. Start your work in Delphi 1, then port to Delphi 2/3.
Any Delphi 2/3 enhancements can be "protected" with IFDEFs in the .PAS files, so the same .PAS file can be used by all Delphi versions:
{$IFDEF ver80}
this is Delphi 1 specific..
{$ENDIF}
{$IFDEF ver90}
this is Delphi 2 specific..
{$ENDIF}
{$IFDEF ver100}
this is Delphi 3 specific..
{$ENDIF}
{$IFDEF ver120}
this is Delphi 4 specific..
{$ENDIF}
{$IFDEF ver130}
this is Delphi 5 specific..
{$ENDIF}
{$IFDEF ver140}
this is Delphi 6 specific..
{$ENDIF}
{$IFDEF ver150}
this is Delphi 7 specific..
{$ENDIF}
{$IFDEF WIN32}
this is specific to Delphi 2 and 3..
{$ENDIF}
{$IFDEF ver93}
this is specific to C++ Builder..
{$ENDIF}
{$IFDEF ver110}
this is specific to C++ Builder 3..
{$ENDIF}
The only serious incompatibility are the .DCR-files. You will have to load them with the Delphi 2/3 Image-Editor, and save them again to convert a 16bit .DCR-file to a 32bit one.
2004. március 16., kedd
Obtain the Julian date
Problem/Question/Abstract:
How to obtain the Julian date
Answer:
function julian(year, month, day: Integer): real;
var
yr, mth: Integer;
noleap, leap, days, yrs: Real;
begin
if year < 0 then
yr := year + 1
else
yr := year;
mth := month;
if (month < 3) then
begin
mth := mth + 12;
yr := yr - 1;
end;
yrs := 365.25 * yr;
if ((yrs < 0) and (frac(yrs) <> 0)) then
yrs := int(yrs) - 1
else
yrs := int(yrs);
days := int(yrs) + int(30.6001 * (mth + 1)) + day - 723244.0;
if days < -145068.0 then
julian := days
else
begin
yrs := yr / 100.0;
if ((yrs < 0) and (frac(yrs) <> 0)) then
yrs := int(yrs) - 1;
noleap := int(yrs);
yrs := noleap / 4.0;
if ((yrs < 0) and (frac(yrs) <> 0)) then
yrs := int(yrs) - 1;
leap := 2 - noleap + int(yrs);
julian := days + leap;
end;
end;
2004. március 15., hétfő
Create a DBGrid that displays graphic fields
Problem/Question/Abstract:
How to create a DBGrid that displays graphic fields
Answer:
unit DBPicGrd;
interface
uses
DBGrids, DB, DBTables, Grids, WinTypes, Classes, Graphics;
type
TDBPicGrid = class(TDBGrid)
protected
procedure DrawDataCell(const Rect: TRect; Field: TField; State: TGridDrawState);
override;
public
constructor Create(AOwner: TComponent); override;
published
property DefaultDrawing default False;
end;
procedure Register;
implementation
constructor TDBPicGrid.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DefaultDrawing := False;
end;
procedure TDBPicGrid.DrawDataCell(const Rect: TRect; Field: TField; State:
TGridDrawState);
var
bmp: TBitmap;
begin
with Canvas do
begin
FillRect(Rect);
if Field is TGraphicField then
try
bmp := TBitmap.Create;
bmp.Assign(Field);
Draw(Rect.Left, Rect.Top, bmp);
finally
bmp.Free;
end
else
TextOut(Rect.Left, Rect.Top, Field.Text);
end;
end;
procedure Register;
begin
RegisterComponents('Custom', [TDBPicGrid]);
end;
end.
2004. március 14., vasárnap
Mouse working only in your application
Problem/Question/Abstract:
I suppose that to somebody it will be he useful this trick.
Have I outlined it to me as a simple exercise of those that you tell yourself to yourself ' that would happen if? '.
It is that the mouse only works in your application. Neither in the Windows desktop, neither in the window's taskbar, neither in any
other place that in your form...
Of course, care with him... if you are happened to print something and the driver of your printer it jumps you with the typical
message ' papaer empty' you won't be able to close the dialogue that it appears... in short, better you prove it and you see if it is
good you for something:
Answer:
function CallBackDelHook(Code: Integer;
wParam: WPARAM;
lParam: LPARAM
): LRESULT; stdcall;
var
DatosMouse: PMouseHookStruct;
Intentos: integer;
{Esta es la funcion CallBack a la cual llamar� el hook.}
{This is the CallBack function called by he Hook}
begin
{Si hay un nuevo evento de raton...}
{if there is a new mouse event...}
if code = HC_ACTION then
begin
{Miramos si existe el fichero}
{if the mapfile exists}
FicheroM := OpenFileMapping(FILE_MAP_READ, False, 'ElReceptor');
{Si no existe, no enviamos nada a la aplicacion receptora}
{If dont, send nothing to receiver application}
if FicheroM <> 0 then
begin
Compartido := MapViewOfFile(FicheroM, FILE_MAP_READ, 0, 0, 0);
{Apuntamos hacia los datos del evento del raton}
DatosMouse := Pointer(lparam);
UnmapViewOfFile(Compartido);
CloseHandle(FicheroM);
end;
end;
{Llamamos al siguiente hook de la cadena}
{call to next hook of the chain}
if Compartido^ <> DatosMouse^.hwnd then
Result := 1
else
Result := CallNextHookEx(HookDeMouse, Code, wParam, lParam);
end;
and the relevant part is this:
if Compartido^ <> DatosMouse^.hwnd then
Result := 1
else
Result := CallNextHookEx(HookDeMouse, Code, wParam, lParam);
that is to say, if the recipient of the message that has captured the hook is our application, we call to the following mouse hook that
has installed in the chain, if it is not this way, because we give the message like treaty, miscarrying this way his processed later for
the application that is...
Well, like in any hook at system level, we will build ourselves first a DLL that is where anger the procedure CallBack of the hook,
and then an example application that will communicate somehow with the DLL.
Therefore:
Hook's DLL
library HookMouse;
{Demo de Hook de Rat�n a nivel de sistema, Radikal.}
uses Windows, Messages;
type
PCompartido = ^THandle;
var
HookDeMouse: HHook;
FicheroM: THandle;
Compartido: PCompartido;
function CallBackDelHook(Code: Integer;
wParam: WPARAM;
lParam: LPARAM
): LRESULT; stdcall;
var
DatosMouse: PMouseHookStruct;
Intentos: integer;
{Esta es la funcion CallBack a la cual llamar� el hook.}
{This is the CallBack function called by he Hook}
begin
{Si hay un nuevo evento de raton...}
{if there is a new mouse event...}
if code = HC_ACTION then
begin
{Miramos si existe el fichero}
{if the mapfile exists}
FicheroM := OpenFileMapping(FILE_MAP_READ, False, 'ElReceptor');
{Si no existe, no enviamos nada a la aplicacion receptora}
{If dont, send nothing to receiver application}
if FicheroM <> 0 then
begin
Compartido := MapViewOfFile(FicheroM, FILE_MAP_READ, 0, 0, 0);
{Apuntamos hacia los datos del evento del raton}
DatosMouse := Pointer(lparam);
UnmapViewOfFile(Compartido);
CloseHandle(FicheroM);
end;
end;
{Llamamos al siguiente hook de la cadena}
{call to next hook of the chain}
if Compartido^ <> DatosMouse^.hwnd then
Result := 1
else
Result := CallNextHookEx(HookDeMouse, Code, wParam, lParam);
end;
procedure HookOn; stdcall;
{Procedure que instala el hook}
{procedure for install the hook}
begin
HookDeMouse := SetWindowsHookEx(WH_MOUSE, @CallBackDelHook, HInstance, 0);
end;
// stops this type of watch
procedure HookOff; stdcall;
begin
{procedure para desinstalar el hook}
{procedure to uninstall the hook}
UnhookWindowsHookEx(HookDeMouse);
end;
exports
{Exportamos las procedures...}
{Export the procedures}
HookOn,
HookOff;
begin
end.
Demo application
In a clean form, put this code in its unit:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls;
const
NombreDLL = 'HookMouse.dll';
type
PCompartido = ^THandle;
THookMouse = procedure; stdcall;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FicheroM: THandle;
Compartido: PCompartido;
HandleDLL: THandle;
HookOn,
HookOff: THookMouse;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
HandleDLL := LoadLibrary(PChar(ExtractFilePath(Application.Exename) +
NombreDLL));
if HandleDLL = 0 then
raise Exception.Create('No se pudo cargar la DLL');
@HookOn := GetProcAddress(HandleDLL, 'HookOn');
@HookOff := GetProcAddress(HandleDLL, 'HookOff');
if not assigned(HookOn) or
not assigned(HookOff) then
raise Exception.Create('No se encontraron las funciones en la DLL' + #13 +
'Cannot find the required DLL functions');
{Creamos el fichero de memoria}
FicheroM := CreateFileMapping($FFFFFFFF,
nil,
PAGE_READWRITE,
0,
SizeOf(THandle),
'ElReceptor');
{Si no se cre� el fichero, error}
if FicheroM = 0 then
raise Exception.Create('Error al crear el fichero' +
'/Error while create file');
{Direccionamos nuestra estructura al fichero de memoria}
Compartido := MapViewOfFile(FicheroM, FILE_MAP_WRITE, 0, 0, 0);
{Escribimos datos en el fichero de memoria}
Compartido^ := Handle;
HookOn;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
{Desactivamos el Hook}
{Uninstall the Hook}
if Assigned(HookOff) then
HookOff;
{Liberamos la DLL}
{Free the DLL}
if HandleDLL <> 0 then
FreeLibrary(HandleDLL);
{Cerramos la vista del fichero y el fichero}
{Close the memfile and the View}
if FicheroM <> 0 then
begin
UnmapViewOfFile(Compartido);
CloseHandle(FicheroM);
end;
end;
end.
Note: If you use this technique in an application with several forms, you will put in ' Compartido' the handle of the form that you will
activate, but it won't receive mouse events. For example, you can make it in the event OnShow of the form...
2004. március 13., szombat
Dynamic SQL Creation: Using a TStrings Descendant to Create a SQL Statement on the Fly
Problem/Question/Abstract:
How do I retrieve the text from a list box to add to the SQL property of a TQuery then create both a Paradox and dBase table?
Answer:
One thing I love about Delphi is that since it's object oriented, you can perform a lot of quick and dirty code tricks that wouldn't be possible with other languages. For instance, the ability to assign values of like properties from one object to another saves so much coding time. Take a list box, for example, as in your question.
What you essentially want to do is create a SQL statement from fields listed in a list box. If you think about it, a list box's Items property and a TQuery's SQL property are both TStrings descendants. This means that you can do a direct assignation between the two.
Actually, that's only half true. You have to format the fields into a proper SQL statement format first, and that requires an intermediate TStrings object.
Luckily though, we can easily accomplish the conversion for field list to SQL statement with a simple function. The function listed below takes a list of fields, a Boolean value to determine whether or not the query is a DISTINCT select, and a table name, and puts all of those together into a valid SQL statement that can easily be
assigned to a TQuery's SQL property. Here's the listing:
{==========================================================
This function will create a SELECT or SELECT DISTINCT SQL
statement given input from a TStrings descendant like a
list. It will properly format the list into field decla-
rations of a SQL statement then, using the supplied
TableNm parameter, will construct an entire statement that
can be assigned to the SQL property of a TQuery.
Params: Distinct SELECT DISTINCT or regular SELECT
TableNm Table name: Should either be a fully
qualified table name, or preceeded by
an alias (ie, ':DbName:MyTable.db')
FieldList Any TStrings descendant will work here,
like the Items property of a TListBox.
==========================================================}
function CreateSelect(Distinct: Boolean;
TableNm: string;
const FieldList: TStrings)
: TStrings;
var
Sql: TStringList;
I: Integer;
buf,
QueryType: string;
begin
//First, instantiate the SQL lines list
Sql := TStringList.Create;
//Determine whether or no this is a regular SELECT
//or a SELECT DISTINCT query.
if Distinct then
QueryType := 'SELECT '
else
QueryType := 'SELECT DISTINCT ';
buf := QueryType;
try
//Now add the fields to the select statement
//Notice that if we're on the last item,
//we don't want to add a trailing comma.
for I := 0 to (FieldList.Count - 1) do
if (I <> FieldList.Count - 1) then
buf := buf + FieldList[I] + ', '
else
buf := buf + FieldList[I];
//Now, put the query together
Sql.Add(buf);
Sql.Add('FROM "' + TableNm + '"');
Result := Sql;
finally
Sql.Free;
end;
end;
To use this, let's say you have a list box call ListBox1, and a query called Query1. You also have a TEdit called Edit1 that holds the table name value. Here's how you'd make the call:
with Query1 do
begin
Active := False;
SQL.Clear;
//This will create a SELECT DISTINCT statement
SQL := CreateSelect(True, Edit1.Text, ListBox1.Items);
Open;
end;
Okay, now that we've finished creating the statement and running the query, we have to move the answers to both Paradox an dBase. This is easily accomplished with a TBatchMove component.
Building on the previous example,. let's say you have a TBatchMove component embedded on your form. We'll call it BatchMove1. To move the answer to a Paradox and a dBase table, you need to use the BatchMove to move the contents of the answer from Query1 to two new tables. The listing below lists an entire procedure that will accomplish this:
procedure GetFieldsAndMove;
var
tblPdox,
tbldBas: TTable;
begin
with Query1 do
begin
Active := False;
SQL.Clear;
//This will create a SELECT DISTINCT statement
SQL := CreateSelect(True, Edit1.Text, ListBox1.Items);
Open;
end;
tblPdox := TTable.Create(nil);
with tblPdox do
begin
Active := False;
DatabaseName := ExtractFilePath(Application.EXEName);
TableName := 'MyPdoxTable';
TableType := ttParadox;
end;
tbldBas := TTable.Create(nil);
with tbldBase do
begin
Active := False;
DatabaseName := ExtractFilePath(Application.EXEName);
TableName := 'MydBaseTable';
TableType := ttDBase;
end;
try
with BatchMove1 do
begin
Source := Query1;
Destination := tblPdox;
Execute;
end;
with BatchMove1 do
begin
Source := Query1;
Destination := tbldBase;
Execute;
end;
finally
tblPdox.Free;
tbldBase.Free;
end;
end;
Again, this is pretty straight-forward stuff. If you need more information on the TBatchMove component, it is well-documented in the online help.
2004. március 12., péntek
How to synchronize two controls
Problem/Question/Abstract:
I have a frame with two panels on it (right and left). The left panel is a pretty standard treeview. The right panel is a representation of the data record for the selected node in the tree view. The right panel is dynamic, that is it is constructed on the fly at run time as the users have the ability to define what fields they wish to show and what the labels are for those fields.
I need the right panel to change the treeview node text when the record in the right panel is posted. The general consensus is that it'd best be done with a callback, but I've never done one before. Can anyone give me a simple example of how to do this?
Answer:
What you are describing is a Mediator Pattern. In essence, you set up a class which is aware of your two (or more) components. Set up properties to record changes and then in the appropriate event handler, simply assign the new values. The Mediator is solely responsible for synchonizing the two.
Very simple example (yours will be slightly more complex, but surprisingly probably won't have too much more code):
TEditBoxMediator = class
private
FIsChanging: boolean;
FFirstBox: TEdit;
FSecondBox: TEdit;
function GetText: string;
procedure SetText(Value: string);
public
property Text: string read GetText write SetText;
constructor Create(const FirstBox, SecondBox: TEdit);
end;
constructor TEditBoxMediator.Create(const FirstBox, SecondBox: TEdit);
begin
inherited Create;
FFirstBox := FirstBox;
FSecondBox := SecondBox;
FIsChanging := False;
end;
function TEditBoxMediator.GetText: string;
begin
Result := FFirstBox.Text;
end;
procedure TEditBoxMediator.SetText(Value: string);
begin
if FIsChanging then
Exit;
FIsChanging := True;
if FFirstBox.Text <> Value then
FFirstBox.Text := Value;
if FSecondBox.Text <> Value then
FSecondBox.Text := Value;
FIsChanging := False;
end;
procedure TForm1.Create {...}
begin
FEditBoxMediator := TEditBoxMediator.Create(Edit1, Edit2);
end;
procedure TForm1.Edit1Change(Sender: TObject);
begin
FEditBoxMediator.Text := Edit1.Text;
end;
and so on.
The idea is that the mediator handles the changes (and uses the internal flag to prevent an endless
loop).
2004. március 11., csütörtök
Sorting a TListView by the column clicked by the user
Problem/Question/Abstract:
How to sort a ListView in ascending or descending order by a given column?
Answer:
Solve 1:
We want the following behaviour for a ListView:
When the user clicks on a column header, the ListView should be sorted by that column
The initial sort order should be ascending. If the user clicks on the same column again, the sort order should be toggled. If the user clicks on another column, the sort order of the new column should be the same as the last sorted column.
For the implementation we need two variables to hold the last column clicked by the user and the current sort order:
var
LastSortedColumn: integer;
Ascending: boolean;
We can initialize them when the form is created:
procedure TForm1.FormCreate(Sender: TObject);
begin
LastSortedColumn := -1;
Ascending := True;
end;
In the ColumnClick event of the ListView we determine the sort order and perform the sort:
procedure TForm1.ListView1ColumnClick(Sender: TObject;
Column: TListColumn);
begin
if Column.Index = LastSortedColumn then
Ascending := not Ascending
else
LastSortedColumn := Column.Index;
TListView(Sender).CustomSort(@SortByColumn, Column.Index);
end;
SortByColumn is a function that should be previously declared and is the function used by CustomSort to compare two items. The value passed to the Data parameter of CustomSort will be passed as the Data parameter to SortByColumn and we use it for the sort column:
function SortByColumn(Item1, Item2: TListItem; Data: integer):
integer; stdcall;
begin
if Data = 0 then
Result := AnsiCompareText(Item1.Caption, Item2.Caption)
else
Result := AnsiCompareText(Item1.SubItems[Data - 1],
Item2.SubItems[Data - 1]);
if not Ascending then
Result := -Result;
end;
Solve 2:
Instead of calling the custum sort procedure we also can use the OnColumnClick and the OnCompare events ion conjunction... That way the compare routine is kept within the class, here a TForm decedant.
Like this:
procedure TfrmMain.lvThingyColumnClick(Sender: TObject; Column: TListColumn);
begin
if Column.Index = fColumnClicked then
fSortAscending := not fSortAscending
else
begin
fSortAscending := true;
fColumnClicked := Column.Index;
end; // else
Screen.Cursor := crHourglass;
try
(Sender as TListView).AlphaSort;
finally
Screen.Cursor := crDefault;
end; // try
end;
procedure TfrmMain.lvThingyCompare(Sender: TObject; Item1, Item2: TListItem; Data:
Integer; var Compare: Integer);
begin
case fColumnClicked of
0: Compare := CompareStr(Item1.Caption, Item2.Caption);
else
Compare := CompareStr(Item1.SubItems[fColumnClicked - 1],
Item2.SubItems[fColumnClicked - 1]);
end; // case
if not fSortAscending then
Compare := -Compare;
end;
Feliratkozás:
Bejegyzések (Atom)