2004. április 14., szerda

Add a horizontal scrollbar to a TListBox

Problem/Question/Abstract:

How to add a horizontal scrollbar to a TListBox

Answer:

A quick way to add the horizontal scroll bar and set its scroll range is to use SendMessage. Put the following command in the OnCreate or OnActivate methods to make the TListbox 300 pixels wide.

uses
ShellAPI

{ ... }
SendMessage(ListBox1.Handle, LB_SETHORIZONTALEXTENT, 300, 0);
{ ... }


2004. április 13., kedd

Create a menu item into the Delphi menu?

Problem/Question/Abstract:

How to create a menu item into the Delphi menu?

Answer:

uses ToolsApi, Menus;

{....}

var
item: TMenuItem;
begin
{get reference to delphi's mainmenu. You can handle it like a common TMainMenu}
with (BorlandIDEServices as INTAServices).GetMainMenu do
begin
item := TMenuItem.Create(nil);
item.Caption := 'A Mewn caption';
Items.Add(item);
end;
end;


2004. április 12., hétfő

Check if the mouse cursor is outside a TForm

Problem/Question/Abstract:

How can I find out if the cursor is leaving a Delphi form?

Answer:

Solve 1:

Add a handler for the CM_MOUSELEAVE message to the form:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Memo1: TMemo;
private
{ Private declarations }
procedure CMMouseEnter(var msg: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var msg: TMessage); message CM_MOUSELEAVE;
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.CMMouseEnter(var msg: TMessage);
begin
if msg.lparam = 0 then
memo1.Lines.add('Entered ' + Name)
else
memo1.Lines.add('Entered ' + TControl(msg.lparam).Name);
end;

procedure TForm1.CMMouseLeave(var msg: TMessage);
begin
if msg.lparam = 0 then
memo1.Lines.add('Left ' + Name)
else
memo1.Lines.add('Left ' + TControl(msg.lparam).Name);
end;

end.


Solve 2:

Place the following code in your form's OnMouseMove event handler, and you'll see SetCapture/ ReleaseCapture in action (plus its side-effects):

procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if (GetCapture < > Handle) then {OnMouseEnter}
begin
Beep;
Caption := 'Hello';
SetCapture(Handle);
end
else if (PtInRect(ClientRect, Point(X, Y))) then {OnMouseOver}
Caption := 'X=' + IntToStr(X) + ':Y=' + IntToStr(Y)
else {OnMouseOut}
begin
Beep;
Caption := 'Goodbye!';
ReleaseCapture;
end;
end;


Solve 3:

You can use a timer (the smaller the interval the more sensitive the program) and in the OnTimer event handler control the mouse position to check if the mouse is inside or outside the form:

procedure TForm1.Timer1Timer(Sender: TObject);
var
pt: TPoint;
begin
GetCursorPos(pt);
if (pt.x < Left) or (pt.x > left + Width) then
Caption := 'Out'
else if (pt.y < Top) or (pt.y > Top + Height) then
Caption := 'Out'
else
Caption := 'In';
end;


2004. április 11., vasárnap

Resize a TForm in steps


Problem/Question/Abstract:

How can I resize a form in steps, not smooth, like the Object Inspector in Delphi?

Answer:

First, declare a message handler for the WM_SIZING message in your form:

TForm1 = class(TForm)
  { ... }
protected
  procedure WmSizing(var Msg: TMessage); message WM_SIZING;
  { ... }
end;

Then define the WmSizing message handler like so:

procedure TForm1.WmSizing(var Msg: TMessage);
const
  STEP = 20;
var
  Side: LongInt;
  Rect: PRect;
begin
  inherited;
  Side := Msg.WParam;
  Rect := PRect(Msg.LParam);
  if (WMSZ_BOTTOM and Side = WMSZ_BOTTOM) then
    Rect^.Bottom := Rect^.Bottom - (Rect^.Bottom mod STEP);
  if (WMSZ_BOTTOMLEFT and Side = WMSZ_BOTTOMLEFT) then
  begin
    Rect^.Bottom := Rect^.Bottom - (Rect^.Bottom mod STEP);
    Rect^.Left := Rect^.Left - (Rect^.Left mod STEP);
  end;
  if (WMSZ_BOTTOMRIGHT and Side = WMSZ_BOTTOMRIGHT) then
  begin
    Rect^.Bottom := Rect^.Bottom - (Rect^.Bottom mod STEP);
    Rect^.Right := Rect^.Right - (Rect^.Right mod STEP);
  end;
  if (WMSZ_LEFT and Side = WMSZ_LEFT) then
    Rect^.Left := Rect^.Left - (Rect^.Left mod STEP);
  if (WMSZ_RIGHT and Side = WMSZ_RIGHT) then
    Rect^.Right := Rect^.Right - (Rect^.Right mod STEP);
  if (WMSZ_TOP and Side = WMSZ_TOP) then
    Rect^.Top := Rect^.Top - (Rect^.Top mod STEP);
  if (WMSZ_TOPLEFT and Side = WMSZ_TOPLEFT) then
  begin
    Rect^.Top := Rect^.Top - (Rect^.Top mod STEP);
    Rect^.Left := Rect^.Left - (Rect^.Left mod STEP);
  end;
  if (WMSZ_TOPRIGHT and Side = WMSZ_TOPRIGHT) then
  begin
    Rect^.Top := Rect^.Top - (Rect^.Top mod STEP);
    Rect^.Right := Rect^.Right - (Rect^.Right mod STEP);
  end;
  Msg.Result := 1;
end;

You can adjust the STEP constant to meet your needs. Likewise, you can make any edge a constant size simply by assigning a valueto it.

2004. április 10., szombat

SCSI-2 device serial number


Problem/Question/Abstract:

For IDE harddisk you can use S.M.A.R.T. API function for extracting serial number. For SCSI it does not work.

Answer:

program ScsiSN;

// PURPOSE: Simple console application that display SCSI harddisk serial number

{$APPTYPE CONSOLE}

uses
  Windows, SysUtils;

//-------------------------------------------------------------

function GetDeviceHandle(sDeviceName: string): THandle;
begin
  Result := CreateFile(PChar('\\.\' + sDeviceName),
    GENERIC_READ or GENERIC_WRITE,
    FILE_SHARE_READ or FILE_SHARE_WRITE,
    nil, OPEN_EXISTING, 0, 0)
end;

//-------------------------------------------------------------

function ScsiHddSerialNumber(DeviceHandle: THandle): string;
{$ALIGN ON}
type
  TScsiPassThrough = record
    Length: Word;
    ScsiStatus: Byte;
    PathId: Byte;
    TargetId: Byte;
    Lun: Byte;
    CdbLength: Byte;
    SenseInfoLength: Byte;
    DataIn: Byte;
    DataTransferLength: ULONG;
    TimeOutValue: ULONG;
    DataBufferOffset: DWORD;
    SenseInfoOffset: ULONG;
    Cdb: array[0..15] of Byte;
  end;
  TScsiPassThroughWithBuffers = record
    spt: TScsiPassThrough;
    bSenseBuf: array[0..31] of Byte;
    bDataBuf: array[0..191] of Byte;
  end;
  {ALIGN OFF}
var
  dwReturned: DWORD;
  len: DWORD;
  Buffer: array[0..SizeOf(TScsiPassThroughWithBuffers) +
  SizeOf(TScsiPassThrough) - 1] of Byte;
  sptwb: TScsiPassThroughWithBuffers absolute Buffer;
begin
  Result := '';
  FillChar(Buffer, SizeOf(Buffer), #0);
  with sptwb.spt do
  begin
    Length := SizeOf(TScsiPassThrough);
    CdbLength := 6; // CDB6GENERIC_LENGTH
    SenseInfoLength := 24;
    DataIn := 1; // SCSI_IOCTL_DATA_IN
    DataTransferLength := 192;
    TimeOutValue := 2;
    DataBufferOffset := PChar(@sptwb.bDataBuf) - PChar(@sptwb);
    SenseInfoOffset := PChar(@sptwb.bSenseBuf) - PChar(@sptwb);
    Cdb[0] := $12; // OperationCode := SCSIOP_INQUIRY;
    Cdb[1] := $01; // Flags := CDB_INQUIRY_EVPD;  Vital product data
    Cdb[2] := $80; // PageCode            Unit serial number
    Cdb[4] := 192; // AllocationLength
  end;
  len := sptwb.spt.DataBufferOffset + sptwb.spt.DataTransferLength;
  if DeviceIoControl(DeviceHandle, $0004D004, @sptwb, SizeOf(TScsiPassThrough),
    @sptwb, len, dwReturned, nil)
    and ((PChar(@sptwb.bDataBuf) + 1)^ = #$80) then
    SetString(Result, PChar(@sptwb.bDataBuf) + 4,
      Ord((PChar(@sptwb.bDataBuf) + 3)^));
end;

//=============================================================
var
  hDevice: THandle = 0;
  sSerNum, sDeviceName: string;

begin
  sDeviceName := ParamStr(1);
  if sDeviceName = '' then
  begin
    WriteLn;
    WriteLn('Display SCSI-2 device serial number.');
    WriteLn;
    WriteLn('Using:');
    WriteLn;
    if Win32Platform = VER_PLATFORM_WIN32_NT then // Windows NT/2000
      WriteLn('  ScsiSN PhysicalDrive0')
    else
      WriteLn('  ScsiSN C:');
    WriteLn('  ScsiSN Cdrom0');
    WriteLn('  ScsiSN Tape0');
    WriteLn;
    Exit;
  end;
  hDevice := GetDeviceHandle(sDeviceName);
  if hDevice = INVALID_HANDLE_VALUE then
    WriteLn('Error on GetDeviceHandle: ', SysErrorMessage(GetLastError))
  else
  try
    sSerNum := ScsiHddSerialNumber(hDevice);
    if sSerNum = '' then
      WriteLn('Error on DeviceIoControl: ',
        SysErrorMessageGetLastError))
else
  WriteLn('Device ' + sDeviceName
    + ' serial number = "', sSerNum, '"');
  finally
  CloseHandle(hDevice);
end;
end.

For more information about SCSI commands:

ftp://ftp.t10.org/t10/drafts/scsi-1/
ftp://ftp.t10.org/t10/drafts/spc/
ftp://ftp.t10.org/t10/drafts/spc2/

2004. április 9., péntek

Eject and close CD-Drive


Problem/Question/Abstract:

Eject and close CD-Drive

Answer:

These two function calls open and close the CD tray.
Because the command "wait" is included in the command string, the function returns after the command has been executed:


uses
  MMSystem;

{ open the CD tray }
mciSendString('Set cdaudio door open wait', nil, 0, 0);

{ close the CD tray }
mciSendString('Set cdaudio door closed wait', nil, 0, 0);

2004. április 8., csütörtök

How to detect if a TMemo has been scrolled


Problem/Question/Abstract:

Is there a way of finding out - during or immediately after the fact - that a control has been scrolled? For instance, say someone moves the scroll thumb in a TMemo. Is there a message I can intercept that says this occurred? I don't really need to know which direction or by how much, just that it happened.

Answer:

Here's unit that shows one way to do this without having to create a descendent. It will let you know about "direct" scrolls, but not about scrolls that happen because of cursor movement through the memo's text, etc. It will also report a scroll if the user merely clicked on the thumb track without moving it (without actually scrolling).

To see the code in action, you will need to fill a TMemo with enough text so that it is necessary to scroll.

unit ScrollCatchU;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    ClearButton: TButton;
    ScrolledLabel: TLabel;
    procedure FormCreate(Sender: TObject);
    procedure ClearButtonClick(Sender: TObject);
  private
    Counter: cardinal;
    procedure Memo1ScrollCatcher(var Message: TMessage);
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

type
  TMyControl = class(TControl);

procedure TForm1.Memo1ScrollCatcher(var Message: TMessage);
begin
  Inc(Counter); {for testing/ diagnostics only ...}
  {Add commented out section below, if you only want the "last" scroll
         message in a sequence}
  if ((Message.Msg = WM_VSCROLL) or (Message.Msg = WM_HSCROLL))
    {  and (TWMVScroll(Message).ScrollCode = SB_ENDSCROLL)   }then
    ScrolledLabel.caption := 'Scrolled';
  {  caption := format('Message: %d   ScrollCode: %d  Counter: %d', [Message.Msg,
                        TWMVScroll(Message).ScrollCode, Counter]);  }
  TMyControl(Memo1).WndProc(Message);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Memo1.WindowProc := Memo1ScrollCatcher;
  Counter := 0;
  ClearButtonClick(nil);
end;

procedure TForm1.ClearButtonClick(Sender: TObject);
begin
  ScrolledLabel.Caption := '';
  {Using a manual "reset" for the "Scrolled" display}
end;

end.

This technique can be used with any TControl descendent.

You might want to add the Windows Mouse Wheel message to the ones that routine is looking for. Something like:

{ ... }
if ((Message.Msg = WM_VSCROLL) or (Message.Msg = WM_HSCROLL)
  or (Message.Msg = WM_MOUSEWHEEL))
  {and (TWMVScroll(Message).ScrollCode = SB_ENDSCROLL)}then
  ScrolledLabel.caption := 'Scrolled';
{ ... }

Of course, if you are just fishing for the SB_ENDSCROLL ScrollCode with the other messages, you'll have to separate the test for this message out a little further.

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