2004. április 7., szerda
Yet Another Credit Card Validator
Problem/Question/Abstract:
A routine to validate and identify Visa/MasterCard/Amex credit cards. Might come handy if you want to perform arbitrary card checking. Original code by Daniel J. Karnes (1990)
Answer:
{-------------------------------------------------
Credit card validator
Returns:
0 : Card is invalid or unknown
1 : Card is a valid AmEx
2 : Card is a valid Visa
3 : Card is a valid MasterCard
-------------------------------------------------}
function Vc(c: string): integer;
var
card: string[21];
Vcard: array[0..21] of byte absolute card;
Xcard: integer;
Cstr: string[21];
y, x: integer;
begin
Cstr := '';
fillchar(Vcard, 22, #0);
card := c;
for x := 1 to 20 do
if (Vcard[x] in [48..57]) then
Cstr := Cstr + chr(Vcard[x]);
card := '';
card := Cstr;
Xcard := 0;
if not odd(length(card)) then
for x := (length(card) - 1) downto 1 do
begin
if odd(x) then
y := ((Vcard[x] - 48) * 2)
else
y := (Vcard[x] - 48);
if (y >= 10) then
y := ((y - 10) + 1);
Xcard := (Xcard + y)
end
else
for x := (length(card) - 1) downto 1 do
begin
if odd(x) then
y := (Vcard[x] - 48)
else
y := ((Vcard[x] - 48) * 2);
if (y >= 10) then
y := ((y - 10) + 1);
Xcard := (Xcard + y)
end;
x := (10 - (Xcard mod 10));
if (x = 10) then
x := 0;
if (x = (Vcard[length(card)] - 48)) then
Vc := ord(Cstr[1]) - ord('2')
else
Vc := 0
end;
2004. április 6., kedd
How to calculate the area of a polygon
Problem/Question/Abstract:
How to calculate the area of a polygon
Answer:
The signed area can be computed in linear time by a simple sum. The key formula is this: If the coordinates of vertex v_i are x_i and y_i, twice the signed area of a polygon is given by:
2 A( P ) = sum_{i = 0}^{n - 1} (x_i y_{i + 1} - y_i x_{i + 1})
Here n is the number of vertices of the polygon. A rearrangement of terms in this equation can save multiplications and operate on coordinate differences, and so may be both faster and more accurate:
2 A( P ) = sum_{i = 0}^{n - 1} ((x_i + x_{i + 1}) (y_{i + 1} - y_i))
To find the area of a planar polygon not in the x-y plane, use:
2 A(P) = abs(N . (sum_{i = 0}^{n - 1} (v_i x v_{i + 1})))
where N is a unit vector normal to the plane. The '.' represents the dot product operator, the 'x' represents the cross product operator, and abs() is the absolute value function.
2004. április 5., hétfő
OutlookExpress Directorie
Problem/Question/Abstract:
How to find the OutlookExpress mailbox dir
Answer:
function GetOutlookExpressDir: string;
var
Reg: TRegistry;
ts, userID: string;
begin
ts := '';
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey('\Software\Microsoft\Outlook Express', False) then
ts := Reg.ReadString('Store Root');
if ts = '' then
begin
if Reg.OpenKey('\Identities', False) then
begin
userID := Reg.ReadString('Default User ID');
if Reg.OpenKey('\Identities\' + userID +
'\Software\Microsoft\Outlook Express\5.0', False) then
ts := Reg.ReadString('Store Root');
end;
end;
finally
if (ts <> '') then
begin
SetLength(userID, 1024);
if (ExpandEnvironmentStrings(pointer(ts), @userID[1], 1024) > 0) then
result := pchar(userID)
else
result := ts;
end;
Reg.CloseKey;
Reg.Free;
end;
end;
2004. április 4., vasárnap
Preventing an application from closing
Problem/Question/Abstract:
I'd like to know if there's some way to prevent a user from closing Windows, or closing an application while it is currently performing a process. Do you know of way?
Answer:
There are two ways to approach this problem. One is strictly Delphi; the other involves creating a message handler for the WM_CLOSE message in Windows. Let's look at the former method first.
The easiest way to decide whether to allow or disallow a user from closing a program is with the OnCloseQuery method of the main form. If you open that method, you'll see the following:
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
end;
The most important part of that method is the CanClose formal parameter. If False, the window will not be allowed to close. If true, the program will close. Here's an example. Let's say that while some background processing is occuring, you have a Boolean variable called "ProcessRunning" set to true during the course of the process. If the user tries to close the program during the run you could do something like this:
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if ProcessRunning then
CanClose := False
else
CanClose := True;
end;
The point to this is to check certain conditions within the program. If the criteria for closing is correct, you can close the window. Otherwise, leave it up.
You'd do the same thing with a custom message handler for the WM_CLOSE message. The only difference is, you have to create the handler. To do this, look at the following section of code taken out of a program that I wrote that is set up to handle WM_CLOSE:
private
procedure WMClose(var Msg: TWMClose); message WM_CLOSE;
public
end;
var
Form1: TForm1;
CloseDown: Boolean;
implementation
{$R *.DFM}
procedure TForm1.WMClose(var Msg: TWMClose);
begin
if not CloseDown then
Msg.Result := 0
else
inherited;
end;
If you're new to creating custom Windows message handlers, while not a trivial thing, it's not that hard to do. It just requires some work. I won't go into a long discussion about Windows message handlers. WM_CLOSE happens to be a fairly simple message to handle, but there are more complex ones out there that take much more space than a simple e- mail reply. So I'll just tell you how to go about handling the message, then let you play with the code:
First, in the private section of the form's type declaration, you must declare the handler. In this case, I've declared it as:
procedure WMClose(var Msg: TWMClose); message WM_CLOSE;
You can name the procedure anything you like.
As far as the implementation is concerned, to deny closure, we have to set the message's result to 0. To allow closure, we just call the inherited WM_CLOSE handler.
procedure TForm1.WMClose(var Msg: TWMClose);
begin
if not CloseDown then
Msg.Result := 0
else
inherited;
end;
As you can see, the principle is exactly the same as using the OnCloseQuery method of the form. But you can also see that to accomplish the same task, a bit more work had to be done. So a good "rule of thumb" is to use Delphi's built-in capabilities as much as possible, and to use only custom message handlers for events that aren't handled by default in Delphi.
2004. április 3., szombat
Writing all controls of given component to TXMLDocument
Problem/Question/Abstract:
Down all controls for component in XMLDocument in simplest way?
Answer:
Simply it seems to pass under the component list and to create appropriate nodes of the XML-document:
for k := 0 to MyComponent.ComponentCount - 1 do
begin
if not (MyComponent.Components[k] is TControl) then
Continue;
// Here create node of the XML-document
end;
However the problem is to satisfy parent - child relations during creation of nodes of the XML-document.
The procedure given below carries out this task by conducting special list of those controls for which are already created XML-document nodes.
Controls corresponding to created nodes are excluded from process of iteration.
// Writing all controls of given component to TXMLDocument according parent-child relations
procedure Get_Component_as_XML(AXMLDoc: TXMLDocument; AComponent: TComponent);
var
k: Integer;
Ctrl: TControl;
List: TList;
XMLNode: IXMLNode;
GrCtrl: TGraphicControl;
procedure Add_WinControlAttributes(AWCtrl: TWinControl; AXMLNode: IXMLNode);
begin
with AXMLNode do
begin
Attributes['Name'] := AWCtrl.Name;
Attributes['Owner'] := AWCtrl.Owner.Name;
Attributes['Left'] := IntToStr(AWCtrl.Left);
Attributes['Top'] := IntToStr(AWCtrl.Top);
Attributes['Width'] := IntToStr(AWCtrl.Width);
Attributes['Height'] := IntToStr(AWCtrl.Height);
// ... add all needed properties
end;
end;
procedure Add_GraphicsControlAttributes(AGCtrl: TGraphicControl; AXMLNode:
IXMLNode);
begin
with AXMLNode do
begin
Attributes['Name'] := AGCtrl.Name;
Attributes['Owner'] := AGCtrl.Owner.Name;
Attributes['Left'] := AGCtrl.Left;
Attributes['Top'] := IntToStr(AGCtrl.Top);
Attributes['Width'] := IntToStr(AGCtrl.Width);
Attributes['Height'] := IntToStr(AGCtrl.Height);
// ... add all needed properties
end;
end;
procedure Add_XML_Node(AWCtrl: TWinControl; AXMLNode: IXMLNode);
var
i: Integer;
WinC: TWinControl;
SubIXMLNode,
NewStock: IXMLNode;
SubCtrl: TControl;
SubGrCtrl: TGraphicControl;
begin
NewStock := AXMLNode.AddChild(AWCtrl.ClassName);
Add_WinControlAttributes(AWCtrl, NewStock);
if AWCtrl.ControlCount > 0 then
for i := 0 to AWCtrl.ControlCount - 1 do
begin
SubCtrl := TControl(AWCtrl.Controls[i]);
if List.IndexOf(SubCtrl) >= 0 then
Continue;
// take a special look at this list
List.Add(Pointer(SubCtrl));
if SubCtrl is TGraphicControl then
begin
SubGrCtrl := TGraphicControl(SubCtrl);
SubIXMLNode := NewStock.AddChild(SubGrCtrl.ClassName);
Add_GraphicsControlAttributes(SubGrCtrl, SubIXMLNode);
end
else if SubCtrl is TWinControl then
begin
WinC := TWinControl(SubCtrl);
Add_XML_Node(WinC, NewStock);
end;
end;
end;
begin
AXMLDoc.XML.Clear;
AXMLDoc.XML.Add(Format('<%s>', [AComponent.Name]));
AXMLDoc.XML.Add(Format('</%s>', [AComponent.Name]));
AXMLDoc.Active := True;
List := TList.Create; // special list to hold controls added to XML
try
for k := 0 to AComponent.ComponentCount - 1 do
begin
if not (AComponent.Components[k] is TControl) then
Continue;
Ctrl := TControl(AComponent.Components[k]);
if List.IndexOf(Ctrl) >= 0 then
Continue;
// take a special look at this list
List.Add(Pointer(Ctrl));
if Ctrl is TGraphicControl then
begin
GrCtrl := TGraphicControl(Ctrl);
XMLNode := AXMLDoc.DocumentElement.AddChild(GrCtrl.ClassName);
Add_GraphicsControlAttributes(GrCtrl, XMLNode);
end
else if Ctrl is TWinControl then
// Recursive process for child controls
Add_XML_Node(TWinControl(Ctrl), AXMLDoc.DocumentElement);
end;
finally
List.Clear;
List.Free;
end;
end;
I do not apply for exclusive novelty, but it seems, that this procedure may be useful to someone.
2004. április 2., péntek
Create a form that saves its component state automatically
Problem/Question/Abstract:
I would like to know how to save a forms appearance once it has been changed by a user.
Answer:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
ExtCtrls;
type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Memo1: TMemo;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
RadioGroup1: TRadioGroup;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
function FormFilename: string;
public
constructor Create(aOwner: TComponent); override;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
close
end;
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
fs: TFilestream;
begin
fs := TFilestream.Create(FormFilename, fmCreate);
try
fs.WriteComponent(self);
finally
fs.free;
end;
end;
function TForm1.FormFilename: string;
begin
Result := ExtractFilePath(ParamStr(0)) + Classname + '.DAT';
end;
constructor TForm1.Create(aOwner: TComponent);
var
fs: TFileStream;
fname: string;
begin
fname := FormFilename;
if FileExists(fname) then
begin
CreateNew(aOwner);
fs := TFileStream.Create(fname, fmOpenread or fmShareDenyWrite);
try
fs.ReadComponent(self);
finally
fs.free;
end;
end
else
inherited Create(aOwner);
end;
end.
2004. április 1., csütörtök
Getting the dates of the first and last day of the month of a given date
Problem/Question/Abstract:
How can I get the dates of the first and last day of the month of a given date?
Answer:
FDOM and LDOM
FDOM returns the date that corresponds to the first day of the same month as the date passed as parameter, while LDOM returns the date that corresponds to the last day of the month (subtracting 1 from the date that corresponds to the first day of the next month).
function FDOM(Date: TDateTime): TDateTime;
var
Year, Month, Day: Word;
begin
DecodeDate(Date, Year, Month, Day);
Result := EncodeDate(Year, Month, 1);
end;
function LDOM(Date: TDateTime): TDateTime;
var
Year, Month, Day: Word;
begin
DecodeDate(Date, Year, Month, Day);
if Month < 12 then
inc(Month)
else
begin
Month := 1;
inc(Year)
end;
Result := EncodeDate(Year, Month, 1) - 1;
end;
Sample call
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(DateToStr(FDOM(Now)));
ShowMessage(DateToStr(LDOM(Now)));
end;
Copyright (c) 2001 Ernesto De Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php
2004. március 31., szerda
Are we On-Line
Problem/Question/Abstract:
Are we On-Line?
Answer:
The following code is a possibility to detect a connection to the internet,
altough it is not 100%.
I have tested it on Windows NT with LAN connections (DSL and cable)
and it worked in these cases.
uses
WinInet;
..
..
function InternetConnected: Boolean;
const
INTERNET_CONNECTION_MODEM = 1; // local system uses a modem to connect to the Internet.
INTERNET_CONNECTION_LAN = 2; // local system uses a local area network to connect to the Internet.
INTERNET_CONNECTION_PROXY = 4; // local system uses a proxy server to connect to the Internet.
INTERNET_CONNECTION_MODEM_BUSY = 8; // local system's modem is busy with a non-Internet connection.
var
dwConnectionTypes: DWORD;
begin
dwConnectionTypes :=
INTERNET_CONNECTION_MODEM +
INTERNET_CONNECTION_LAN +
INTERNET_CONNECTION_PROXY;
Result := InternetGetConnectedState(@dwConnectionTypes, 0);
end;
Note: this solution only works if IE is installed, so it would fail on
'older' machines, like most Windows NT 4 computers. You app would then
display an error during program startup if you referred to Wininet.
2004. március 30., kedd
Controlling Margins when printing RichEdit contents
Problem/Question/Abstract:
How can I control margins when printing text that I have loaded into a TRichEdit?
Answer:
Printing from a RichEdit is really rather easy - all you need to do is to call the Print method:
RichEdit1.Print(const Caption: string);
The Caption parameter shown here specifies the title that appears in the Print queue. Therefore you would, for example, call something like:
RichEdit1.Print(MyAppName + ': ' + DocumentTitle);
From this call the system will carefully format and print the contents of the RichEdit automatically over the required number of pages. That is all well and good, but it does have an unwanted side effect - there is no control over the margins whatsoever. It will simply use the default margins as reported by the Printer when it returns its printable page size.
In order to be able to define the margins you need to know a number of things... The available space on the page, the unprintable area of the page, whether to calculate the margins as Inches or Centimetres, and so on. Much of this can be retrieved from the Printer object, and the rest we will need to provide in our code.
The first thing to decide is how to determine the measurements. You could pass this as a String (e.g. 'inches' or 'centimetres'), you could pass it as a number (e.g. 1 for inches, 2 for centimetres) but perhaps the easiest way is to declare your own data type that will make the code easier to read. For this example I have defined TRichTextMeasurements in the Interface section of the unit:
type
TRichTextMeasurements = (rtmNone, rtmInches, rtmCentimetres);
Now we can determine whether to use the default margins (rtmNone) or to create our own margins in the selected measurement.
Now all we need is the code to implement the margins if needed. This example function accepts parameters to describe the margins required, the type of measurements to be used for creating margins and the number of copies to be printed.
function PrintRichText(RTLeftMargin, RTRightMargin, RTTopMargin, RTBottomMargin:
Extended;
RichTextMeasurement: TRichTextMeasurements; Copies: Integer): Boolean;
var
��PixelsX, PixelsY, LeftSpace, TopSpace: Integer;
��LeftMargin, RightMargin, TopMargin, BottomMargin: Extended;
begin
Result := False; // default return value
��if RichTextMeasurement <> rtmNone then
����begin
������ // get pixels per inch
������PixelsX := GetDeviceCaps(Printer.Handle, LOGPIXELSX);
������PixelsY := GetDeviceCaps(Printer.Handle, LOGPIXELSY);
������ // get non-printable margins
������LeftSpace := GetDeviceCaps(Printer.Handle, PHYSICALOFFSETX);
������TopSpace := GetDeviceCaps(Printer.Handle, PHYSICALOFFSETY);
������LeftMargin := RTLeftMargin;
������RightMargin := RTRightMargin;
������TopMargin := RTTopMargin;
������BottomMargin := RTBottomMargin;
������ // If the measurement is set in Centimetres, recalculate
������if RichTextMeasurement = rtmCentimetres then
��������begin
����������LeftMargin := LeftMargin / 2.54;
����������RightMargin := RightMargin / 2.54;
����������TopMargin := TopMargin / 2.54;
����������BottomMargin := BottomMargin / 2.54;
��������end;
�������� // Set the Margins
��������R.Left := Round(PixelsX * LeftMargin) - LeftSpace;
��������R.Right := Printer.PageWidth - Round(PixelsX * RightMargin) - LeftSpace;
��������R.Top := Round(PixelsY * TopMargin) - TopSpace;
��������R.Bottom := Printer.PageHeight - Round(PixelsY * BottomMargin) - TopSpace;
��������RichEdit1.PageRect := R;
��������Application.ProcessMessages;
����end;
// Print the required number of copies
��while Copies > 0 do
����begin
������RichEdit1.Print('MyApp: Copy ' + IntToStr(Copies));
������Dec(Copies);
������Application.ProcessMessages;
����end;
Result := True;
end;
To call the example code to print one copy with a 1 inch margin all round, you could do something like this:
procedure TForm1.PrintButtonClick(Sender: TObject);
begin
��if PrintRichText(1, 1, 1, 1, rtmInches, 1) then
����ShowMessage('Printing was successful')
��else
����ShowMessage('Printing failed');
end;
Note that if you want to use the default margins you still have to pass a number for each margin in the function call. What that number is does not matter as they are all ignored, but perhaps for clarity using a zero would be best:
procedure TForm1.PrintButtonClick(Sender: TObject);
begin
if PrintRichText(0, 0, 0, 0, rtmNone, 1) then
ShowMessage('Printing was successful')
else
ShowMessage('Printing failed');
end;
This example can easily be extended to provide visual print progress feedback, or to add margin measurements in millimetres. However, it will not replace a full implementation as provided by commercial Word Processing products. On the other hand, for many purposes it will more than suffice.
2004. március 29., hétfő
Search for duplicate files on large drives
Problem/Question/Abstract:
I have a list of items that I will need to deal with (looking for duplicate files on a drive) that can be upto 2 to 5 million in size. So I will be populating this list and then searching it over and over and over. Normally when dealing with smaller lists like this I would simply use a TStringList and attach an object. However, this seems a little large for TStringList and the main reason, the searching with IndexOf, I don't think is reason enough to use it. So what I am looking for is a list of some sort (TObjectList ?) that is fast and good to deal with and can easily handle this size of entries. It would be really nice it there was a way to create multiple indexes into the in-memory list, as that would greatly speed up my processing of the information. The best solution would be an in-memory database of some sort (at least I think it would be), but my issue with in-memory databases is that of the String sizes for File Name and directory. If I use a regular String variable in an object, then the size can be variable. If I use a standard DB field, then the size in the ones I have seen are all static. So I have to define a huge field to handle all file names which wastes space on all other entries in the list. Any thoughts as the best container to handle this sort of thing?
Answer:
{$A+,B-,D-,E+,F-,G+,I-,L-,N-,O-,P-,Q-,R-,S-,T-,V-,X-,Y-}
program FindDup;
{$APPTYPE CONSOLE} // 2002-12-16 - Delphi 32 console app
{Usage: FINDDUP [D:]
This program finds all duplicate files on the specified drive. The algorithm uses a hash table where each hash value contains a linked list of files that match a given hash. Every file found is inserted into the hash table linked list unless it's already there and therefore a duplicate. All duplicates are added to a red-black tree, where each node contains the file ame and a pointer to a linked list of records containing size, date, and path information.
This program can be compiled in either real or protected modes. Protected mode will allow it to search larger drives. Informal benchmarks on a 1.6 Gig drive with > 900 directories, Pentium 90, compiled for p-mode:
TEST 16 sec. (simple do-nothing recursive dir searcher)
FINDDUP 18 sec. - 16 = 2 sec.
REP-DPMI 36 sec. - 16 = 20 sec.
Subtracting the overhead of FindFirst/ FindNext, this program runs in about 2 seconds as compared to REP-DPMI's 20 seconds. Without ignoring the overhead, it's still twice as fast. Please note that this program is pure pascal.}
{$DEFINE DRBOB} // Do not search hidden directories or find hidden files
{.$DEFINE SAFE}// Checks memory allocations for out of memory conditions
{.$DEFINE CLEANUP}// Frees allocated memory - slows things down a bit
uses
SysUtils;
const
DosDelimSet: set of Char = ['\', ':', #0];
MaxHash = 16381; {largest prime number < 16K}
type
PathStr = string;
NameString = string[12];
St2 = string[2];
pPath = ^PathRecord; {we will only keep one copy of each unique directory path}
PathRecord = record
Next: pPath;
Path: PathStr;
end;
pDataRec = ^DataRec; {detailed information unique to each dupliacte}
DataRec = record
Time: longint;
Size: longint;
Path: pPath;
Next: pDataRec;
end;
link = ^RBTreeNode;
RBTreeNode = record {Red/ black tree node}
Key: NameString; {Name of file}
red: boolean;
l, r: link;
DataP: pDataRec; {linked list of detail information}
end;
pFileRec = ^MyFileRec;
MyFileRec = record
{Hash table record. There will only be one record for each duplicate file name}
Name: NameString;
Time: longint;
Size: longint;
Path: pPath;
Node: link; {let's quickly insert duplicate into tree}
next: pFileRec; {next record in linked list}
end;
tHashTable = array[0..MAXHASH] of pFileRec;
var
Head, z: link;
HashTable: ^tHashTable;
PathHead, TempPathHead: pPath;
OldName: NameString;
procedure RBTreeInitialize;
{Initialize red/ black tree}
begin
New(Z);
{$IFDEF SAFE}
if Z = nil then
exit;
{$ENDIF}
z^.l := z;
z^.r := z;
z^.red := false;
New(Head);
{$IFDEF SAFE}
if Head = nil then
exit;
{$ENDIF}
Head^.r := z;
Head^.l := z;
Head^.Key := '';
Head^.Red := false;
end;
function Rotate(const Value: MyFileRec; y: link): link;
var
c, gc: link;
begin
if Value.Name < Y^.Key then
c := y^.l
else
c := y^.r;
if Value.Name < c^.Key then
begin
gc := c^.l;
c^.l := gc^.r;
gc^.r := c;
end
else
begin
gc := c^.r;
c^.r := gc^.l;
gc^.l := c;
end;
if Value.Name < Y^.Key then
y^.l := gc
else
y^.r := gc;
Rotate := gc;
end;
function Split(const Value: MyFileRec; gg, g, p, x: link): link;
begin
x^.red := true;
x^.l^.red := false;
x^.r^.red := false;
if p^.red then
begin
g^.red := true;
if (Value.Name < g^.Key) <> (Value.Name < p^.Key) then
p := Rotate(Value, g);
x := rotate(Value, gg);
x^.red := false;
end;
Head^.r^.red := false;
split := x;
end;
function RBTreeInsert(const Value: MyFileRec; x: link): link;
{Insert file record into red/ black tree}
var
gg, g, p: link;
begin
p := x;
g := x;
repeat
gg := g;
g := p;
p := x;
if Value.Name < x^.Key then
x := x^.l
else
x := x^.r;
if x^.l^.red and x^.r^.red then
x := split(Value, gg, g, p, x);
until
x = z;
new(x);
{$IFDEF SAFE}
if x = nil then
exit;
{$ENDIF}
x^.Key := Value.Name;
New(x^.DataP);
{$IFDEF SAFE}
if x^.DataP = nil then
exit;
{$ENDIF}
x^.DataP^.Next := nil;
x^.DataP^.Time := Value.Time;
x^.DataP^.Size := Value.Size;
x^.DataP^.Path := Value.Path;
x^.l := z;
x^.r := z;
if Value.Name < p^.Key then
p^.l := x
else
p^.r := x;
RbTreeInsert := x;
x := Split(Value, gg, g, p, x);
end;
procedure Traverse(p: link);
{Traverse red/ black tree, printing out results}
var
TempQ, q: pDataRec;
begin
if (p^.l <> z) and (p^.l <> nil) then
Traverse(p^.l);
if (p <> head) then
begin
if p^.Key <> OldName then
begin
OldName := p^.Key;
writeln(OldName);
end;
q := p^.DataP;
while q <> nil do
begin
with q^ do
writeln(size: 10, ' ', FormatDateTime('yyyy-mm-dd hh:nn:ss',
FileDateToDateTime(Time)), ' ', Path^.Path);
{$IFDEF CLEANUP}
TempQ := q;
q := q^.Next;
Dispose(TempQ);
{$ELSE}
q := q^.Next;
{$ENDIF}
end;
writeln;
end;
if (p^.r <> z) and (p^.r <> nil) then
Traverse(p^.r);
{$IFDEF CLEANUP}
Dispose(p);
{$ENDIF}
end;
function AddBackSlash(const DirName: string): string;
{Add a default backslash to a directory name}
begin
if DirName[Length(DirName)] in DosDelimSet then
AddBackSlash := DirName
else
AddBackSlash := DirName + '\';
end;
function Hash(const Key: NameString): word;
var
h: word;
j: integer;
Len: integer;
begin
Len := Length(Key);
h := ord(Key[1]);
for j := 2 to Len do
begin
h := ((h * 32) + Ord(Key[j])) mod MAXHASH;
end;
Hash := h;
end;
procedure Add(var SR: tSearchRec; DirP: pPath);
{Add a new search record/ path to the hash table}
var
p, q, r: pFileRec;
h: word;
TempData: pDataRec;
begin
h := Hash(SR.Name);
New(r);
{$IFDEF SAFE}
if r = nil then
exit;
{$ENDIF}
r^.Name := SR.Name;
r^.Time := SR.Time;
r^.Size := SR.Size;
r^.Path := DirP;
r^.Next := nil;
r^.Node := nil;
p := HashTable^[H];
if p = nil then
begin {Hash slot not used}
HashTable^[h] := r;
end
else
begin
q := p;
while (p <> nil) and (p^.Name < SR.Name) do
begin
q := p;
p := p^.Next;
end;
if (p <> nil) and (p^.Name = SR.Name) then
begin {Found duplicate file}
if p^.Node = nil then
begin {was not already in tree}
p^.Node := RBTreeInsert(p^, Head);
{save link so we don't have to search tree next time}
end;
New(TempData);
{$IFDEF SAFE}
if TempData = nil then
exit;
{$ENDIF}
TempData^.Time := Sr.Time;
TempData^.Size := Sr.Size;
TempData^.Path := DirP;
TempData^.Next := p^.Node^.DataP; {Add to linked list on tree node}
p^.Node^.DataP := TempData;
Dispose(r); {didn't need it after all}
end
else
begin {Not a duplicate}
if p = q then
begin {Add at start of linked list}
HashTable^[H] := r;
r^.Next := P;
end
else
begin {Insert into linked list}
q^.Next := r;
r^.Next := p;
end;
end;
end;
end;
procedure Find(const Path: PathStr);
{Recursive file/directory searcher}
var
Sr: tSearchRec;
DirP: pPath;
r: integer;
begin
New(DirP);
{$IFDEF SAFE}
if DirP = nil then
exit;
{$ENDIF}
DirP^.Path := Path;
DirP^.Next := PathHead;
PathHead := DirP;
r := FindFirst(AddBackSlash(Path) + '*.*', faAnyFile, Sr);
while r = 0 do
begin
{$IFDEF DRBOB} {only do non-hidden directories}
if ((Sr.Attr and faDirectory) <> 0) and ((Sr.Attr and faHidden) = 0) then
begin
{$ELSE} {do them all}
if (Sr.Attr and Directory) <> 0 then
begin
{$ENDIF}
if Sr.Name[1] <> '.' then
Find(AddBackSlash(Path) + Sr.Name);
r := 0;
end
else
begin
{$IFDEF DRBOB}
if (Sr.Attr and faHidden) = 0 then {Only do non-hidden files}
{$ENDIF}
Add(Sr, DirP);
end;
r := FindNext(Sr);
end;
end;
function HeapFunc(Size: Word): Integer; far;
begin
HeapFunc := 1;
end;
procedure Init;
begin
OldName := '';
PathHead := nil;
{$IFDEF SAFE}
HeapError := @HeapFunc;
{$ENDIF}
New(HashTable);
{$IFDEF SAFE}
if HashTable = nil then
halt;
{$ENDIF}
FillChar(HashTable^, sizeof(HashTable^), 0);
RBTreeInitialize;
end;
procedure Process;
begin
Find(ParamStr(1) + '\');
Traverse(Head);
end;
procedure Done;
var
i: integer;
q, tempq: pFileRec;
begin
{$IFDEF CLEANUP}
Dispose(Z);
for i := 0 to MAXHASH - 1 do
begin
if HashTable^[i] <> nil then
begin
q := HashTable^[i];
while q <> nil do
begin
tempq := q^.next;
Dispose(q);
q := tempq;
end;
end;
end;
Dispose(HashTable);
TempPathHead := PathHead;
while PathHead <> nil do
begin
TempPathHead := PathHead^.Next;
FreeMem(PathHead, Length(PathHead^.Path) + 5);
PathHead := TempPathHead;
end;
{$ENDIF}
end;
begin
Init;
Process;
Done;
end.
2004. március 28., vasárnap
How to shift focus between buttons programmatically
Problem/Question/Abstract:
I have 4 buttons on a form, let's say button1 and button2 on the left side on the form and button3 and button4 on the right side on the form. When Button1 has the focus and I press the RightArrow I want to have Button3 to get the focus instead of Button2. When Button3 has the focus and I press the LeftArrow I want to have Button1 to get the focus. I've tried the onkeydown event on the button but it ignores to trap the arrowkeys.
Answer:
Buttons do not process navigation keys, so they go to the form in the guise of CM_DIALOGKEY messages and the form processes them to move to the next/ previous control in tab order. You may be able to achieve what you want by simply changing the tab order of your buttons (assuming they are all sitting on the same parent control).
To handle this all yourself you would add a handler for the CM_DIALOGKEY message to the form.
{form private section}
procedure CMDialogKey(var msg: TCMDialogKey); message CM_DIALOGKEY;
procedure TForm1.CMDialogKey(var msg: TCMDialogKey);
begin
case Msg.Charcode of
VK_RIGHT:
begin
if ActiveControl = Button1 then
begin
Button3.Setfocus;
msg.result := 1; {mark key handled}
Exit;
end;
if ActiveControl = Button2 then
begin
Button4.Setfocus;
msg.result := 1; {mark key handled}
Exit;
end;
end;
VK_LEFT:
begin
if ActiveControl = Button3 then
begin
Button1.Setfocus;
msg.result := 1;
Exit;
end;
if ActiveControl = Button4 then
begin
Button2.Setfocus;
msg.result := 1;
Exit;
end;
end;
end;
inherited;
end;
end;
2004. március 27., szombat
How to assign an application to have a smaller percentage of the CPU cycles
Problem/Question/Abstract:
How to assign an application to have a smaller percentage of the CPU cycles
Answer:
The rest of this may take a little time, and is quite CPU intensive, so try and drop to a lower priority if possible. Drop to low priority for CPU-intensive parts.
saved_priority_class := GetPriorityClass(GetCurrentProcessID);
if saved_priority_class <> 0 then
SetPriorityClass(GetCurrentProcess, IDLE_PRIORITY_CLASS);
{ CPU intensive stuff here ... }
{Restore normal priority}
if saved_priority_class <> 0 then
SetPriorityClass(GetCurrentProcess, saved_priority_class);
2004. március 26., péntek
Definitions of PRIVATE, PROTECTED, PUBLIC, and PUBLISHED sections of a unit
Problem/Question/Abstract:
What do the PRIVATE, PROTECTED, PUBLIC and PUBLISHED sections of a unit mean?
Answer:
They define the level of visibility of properties and methods of an object. In a nutshell, they are as follows:
PRIVATE - Things contained in this section are private to the object. External objects do not have access to any elements contained here.
PROTECTED - Similar to private with one exception: Descendants of the object have access to the methods and properties contained here.
PUBLIC - All external objects have access to elements here.
PUBLISHED - Similar to PUBLIC, but properties listed here show up at design time under the Object Inspector.
These sections really come into play when you're building components. Typically, you'll put the local field variables assigned to properties in the PRIVATE section, along with functions and procedures that act only within the scope of the object itself. In the PROTECTED methods, if you know the object will be inherited at some point, you'll put properties, functions and procedures to give access to your descendants, but maintain privacy from external objects. In the PUBLIC section, you'll place methods and procedures that usually don't have a corresponding property, but require full access by other entities; or, insert properties that you don't want visible in the Object Inspector. The PUBLISHED section by convention is for properties only, though I've put procedures there just to see if I still had access to them.
TForms have PRIVATE and PUBLIC sections as well. In most cases you won't put them to use; however, there will be times when you want to add functionality and capabilities to the form that need to be assigned levels of visibility.
Play around with this stuff. The more you understand it, the more you'll understand object-oriented programming. By the way, I suggest getting a book on general object-oriented programming principles. Understanding the theory behind objects will help you get a better handle on Delphi programming.
2004. március 25., csütörtök
How to convert a hex color to its HTML counterpart
Problem/Question/Abstract:
How to convert a hex color to its HTML counterpart
Answer:
Solve 1:
This may run faster using shl/ shr and the bitwise AND operator to separate R, G and B parts before converting to a string:
function ColorToHTML(C: TColor): string;
begin
Result := IntToHex(C, 6);
Result := '#' + Copy(Result, 5, 2) + Copy(Result, 3, 2) + Copy(Result, 1, 2);
end;
function HTMLToColor(C: string): TColor;
begin
if Copy(C, 1, 1) = '#' then
C := Copy(C, 2, Length(C));
Result := StrToInt('$' + Copy(C, 5, 2) + Copy(C, 3, 2) + Copy(C, 1, 2));
end;
Solve 2:
The HTML color code is the other way round as TColor :
TColor = $DDBB ggrr
HTML = $00 RRGGBB
So you just have to swap bytes:
{ ... }
var
HTMLColor, mycolor: Integer;
{ ... }
HTMLColor := (((MyColor and $FF) shl 16) or ((MyColor and $FF00)) or
((MyColor and $FF0000) shr 16));
YourHTMLColor := IntToHex(HTMLColor, 8);
Feliratkozás:
Bejegyzések (Atom)