2004. június 16., szerda

Implementing 'Drag Scrolling' in a Grid (as Excel has..)


Problem/Question/Abstract:

When dragging an object over a grid, if the cell you require is not visible, or only partially visible, it would be useful to have the grid automatically scroll to bring the cell into view (a kind of drag-hot-tracking).

Excel does it, Lotus 123 does it, now let's make a humble TStringGrid do it.

This builds on the article/ tutorial of 'Published Objects in Components'

Answer:

This article builds on information given in the article 'Published Objects in Components' (ID 3039) about how to add 'dropdown' properties in the object inspector. You do not need to read or understand that article, but it would serve as background reading!

To provide a 'drag-scrolling' mechanism to a grid, the main principles are:

override the dragover method, and within it:  check whether the cursor is within certain user-defined margins, if within the margins, start the drag-scroll process, initialising a timer  if not within the margins, stop the timer
provide a timer method which will check (at a user-defined interval) whether the cursor still falls within the margin, if so, continue scrolling

The timer is used, as if the user stops moving, but is still over the grid, it will still need checking (a dragmove will only occur when the mouse actually moves).

To facilitate all this, and provide a suite of options, I have gone the route of providing a new object (TDragScrollOptions) which encapsulates all the requied options - margins, timer values, etc. This, in turn, has some objects defined within itself as well (TDragScrollDelays, TDragScrollMargins)..

The structure is as follows:

TDragScrollOptions

property Active: boolean;
  property Delays: TDragScrollDelays;
    |
      - property InitialDelay: integer;
      - property RepeatDelay: integer;
  property Margins: TDragScrollMargins;
          |
            - property TopMargin: integer;
            - property BottomMargin: integer;
            - property LeftMargin: integer;
            - property RightMargin: integer;
end;

The Delays work as one would now expect with any windows application - an initial wait, then a faster response afterwards - hence the Initial and Repeat delays.

The Margins are application from the edges of the component. If the cursor falls between an edge and its repective margin, a scroll can happen.

An Event has been added to allow the developer to monitor the drag scrolling, with an option to cancel the operation (the CanScroll parameter):

TDragScrollEvent = procedure(Sender: TObject; TopRow, LeftCol: LongInt; var
  DragScrollDir: TDragScrollDirection; var CanScroll: boolean) of object;

Enough waffle!! Here is the base component. Copy it into a unit, save and install! Feel free to take out the drag scroll stuff for your own favourite grid (my most used grid has features from all over the place - I wrote this part all myself tho' - no copyright infringement!).

If you use the component, or take the drag scroll engine elsewhere, please let me know (just out of interest really!) - duncanparsons@hotmail.com

unit DragScrollGrid;

{© Duncan Parsons 2002
This Component is freeware, but I am interested in where it ends up!!
Drop me a line on duncanparsons@hotmail.com

Grid with 'Drag Scroll' Option - when an object is dragged over the control,
                                  it will scroll to reveal the hidden cells as needed

If you make any good changes, let me know!
Happy Coding
Duncan Parsons}

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  Grids, ExtCtrls;

type
  //For Drag-Scrolling
  TDragScrollDelays = class(TPersistent)
  private
    fInitialDelay: integer;
    fRepeatDelay: integer;
  published
    property InitialDelay: integer read fInitialDelay write fInitialDelay default
      1000;
    property RepeatDelay: integer read fRepeatDelay write fRepeatDelay default 250;
  end;
  TDragScrollMargins = class(TPersistent)
  private
    fTopMargin: integer;
    fBottomMargin: integer;
    fLeftMargin: Integer;
    fRightMargin: Integer;
  published
    property TopMargin: integer read fTopMargin write fTopMargin default 50;
    property BottomMargin: integer read fBottomMargin write fBottomMargin default 50;
    property LeftMargin: Integer read fLeftMargin write fLeftMargin default 50;
    property RightMargin: Integer read fRightMargin write fRightMargin default 50;
  end;

  TDragScrollOptions = class(TPersistent)
  private
    fActive: Boolean;
    fDelays: TDragScrollDelays;
    fMargins: TDragScrollMargins;
  public
    constructor create; //override;
    destructor destroy; override;
  published
    property Active: boolean read fActive write fActive;
    property Delays: TDragScrollDelays read fDelays write fDelays;
    property Margins: TDragScrollMargins read fMargins write fMargins;
  end;

  TDragScrollDirections = (dsdUp, dsdDown, dsdLeft, dsdRight);
  TDragScrollDirection = set of TDragScrollDirections;
  TDragScrollEvent = procedure(Sender: TObject; TopRow, LeftCol: LongInt; var
    DragScrollDir: TDragScrollDirection; var CanScroll: boolean) of object;

type
  TDragScrollGrid = class(TStringGrid)
  private
    { Private declarations }
    //Drag Scrolling
    fDragScrollOptions: TDragScrollOptions;
    fTmr: TTimer;
    fDragScrollDirection: TDragScrollDirection;
    fOnDragScroll: TDragScrollEvent;
    procedure SetDragScrollOptions(Value: TDragScrollOptions);
  protected
    { Protected declarations }
    procedure DragOver(Source: TObject; X, Y: Integer; State: TDragState; var Accept:
      Boolean); override;
    procedure TimerProc(Sender: Tobject);
  public
    { Public declarations }
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    { Published declarations }
    property OnDragScroll: TDragScrollEvent read fOnDragScroll
      write fOnDragScroll;
    property DragScrollOptions: TDragScrollOptions read fDragScrollOptions write
      SetDragScrollOptions;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Samples', [TDragScrollGrid]);
end;

//---TDragScrollOptions

constructor TDragScrollOptions.create;
begin
  inherited;
  fDelays := TDragScrollDelays.create;
  fDelays.InitialDelay := 1000;
  fDelays.RepeatDelay := 250;
  fMargins := TDragScrollMargins.create;
  fMargins.TopMargin := 50;
  fMargins.BottomMargin := 50;
  fMargins.LeftMargin := 50;
  fMargins.RightMargin := 50;
end;

destructor TDragScrollOptions.destroy;
begin
  fDelays.free;
  fMargins.free;
  inherited;
end;

//---TDragScrollGrid

constructor TDragScrollGrid.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  fDragScrollOptions := TDragScrollOptions.create;
end;

destructor TDragScrollGrid.Destroy;
begin
  if Assigned(fTmr) then
  begin
    fTmr.enabled := false;
    fTmr.Free;
  end;
  fDragScrollOptions.free;

  inherited Destroy;
end;

//---Drag Scroll initialisation and finalisation

procedure TDragScrollGrid.DragOver(Source: TObject; X, Y: Integer; State: TDragState;
  var Accept: Boolean);
var
  CurrentlyScrolling: boolean;
begin
  if not (fDragScrollOptions.Active) then
  begin
    if Assigned(fTmr) then
    begin
      fTmr.enabled := false;
      fTmr.free;
      fTmr := nil;
    end;
    inherited;
    exit;
  end;
  if fDragScrollDirection = [] then
    CurrentlyScrolling := false
  else
    CurrentlyScrolling := true;
  fDragScrollDirection := [];
  case State of
    dsDragEnter, dsDragMove:
      begin
        //Moving in the Grid, Check the Borders
        if y Include(fDragScrollDirection, dsdUp)
  else
    if y > (Height - fDragScrollOptions.Margins.BottomMargin) then
      Include(fDragScrollDirection, dsdDown);
    if x Include(fDragScrollDirection, dsdLeft)
  else
    if x > (width - fDragScrollOptions.Margins.RightMargin) then
      Include(fDragScrollDirection, dsdRight);
    //Any Borders hit?
    if fDragScrollDirection = [] then
    begin
      //Turn Timer off
      if Assigned(fTmr) then
      begin
        fTmr.Enabled := false;
        fTmr.free;
        fTmr := nil;
      end;
    end
    else
    begin
      if not (Assigned(fTmr)) then
      begin
        fTmr := TTimer.Create(Parent);
        fTmr.Interval := fDragScrollOptions.Delays.InitialDelay;
        fTmr.OnTimer := TimerProc;
        fTmr.enabled := true;
      end
      else
      begin
        //Reset the Timer if a new scroll is required
        if not (CurrentlyScrolling) then
          fTmr.Interval := fDragScrollOptions.Delays.InitialDelay;
      end;
    end;
  end;
  dsDragLeave:
  begin
    if Assigned(fTmr) then
    begin
      fTmr.Enabled := false;
      fTmr.free;
      fTmr := nil;
    end;
  end;
end;
inherited;
end;

//---Drag Scroll Timer..

procedure TDragScrollGrid.TimerProc(Sender: Tobject);
var
  CanScroll: Boolean;
  DSD: TDragScrollDirection;
begin
  if not (fDragScrollOptions.Active) then
  begin
    fTmr.Enabled := false;
    fTmr.free;
    fTmr := nil;
    exit;
  end;
  fTmr.Interval := fDragScrollOptions.Delays.RepeatDelay;
  //Do Scroll if User is OK with it
  DSD := fDragScrollDirection;
  if Assigned(fOnDragScroll) then
  begin
    CanScroll := true;
    fOnDragScroll(Self, TopRow, LeftCol, DSD, CanScroll);
    if not (CanScroll) then
      exit;
  end;
  //Allow scroll
  if dsdUp in DSD then
  begin
    if TopRow > FixedRows then
      TopRow := TopRow - 1;
  end;
  if dsdDown in DSD then
  begin
    if (TopRow + VisibleRowCount) < (RowCount) then
      TopRow := TopRow + 1;
  end;
  if dsdLeft in DSD then
  begin
    if LeftCol > FixedCols then
      LeftCol := LeftCol - 1;
  end;
  if dsdRight in DSD then
  begin
    if (LeftCol + VisibleColCount) < (ColCount) then
      LeftCol := LeftCol + 1;
  end;
end;

//---

procedure TDragScrollGrid.SetDragScrollOptions(Value: TDragScrollOptions);
begin
  fDragScrollOptions.Assign(Value);
  if csDesigning in ComponentState then
    invalidate;
end;

end.


Component Download: DragScrollGrid.zip

2004. június 15., kedd

How to avoid the "Drive A Not Ready" error


Problem/Question/Abstract:

How to avoid the "Drive A Not Ready" error

Answer:

When your program accesses drive 'A', it would be handy to intercept the 'Drive Not Ready' system error message. You can create your own generic function to test any drive letter.


function DiskInDrive(Drive: Char): Boolean;
var
  ErrorMode: word;
begin
  Drive: = UpCase(Drive);
  if not (Drive in ['A'..'Z']) then
    raise EConvertError.Create('Not a valid drive ID');
  ErrorMode := SetErrorMode(SEM_FailCriticalErrors);
  try
    if DiskSize(Ord(Drive) - $40) = -1 then
      DiskInDrive := False
    else
      DiskInDrive := True;
  finally
    SetErrorMode(ErrorMode);
  end;
end;


Your function forces the passed drive letter to uppercase and assures it is a valid drive. Then you turn off the system error reporting and perform a disk operation. Your function will return True indicating the disk is present or False if there was an error. The last bit of housekeeping is to turn on the system error reporting.

2004. június 14., hétfő

Base64 (MIME) Encode and Decode


Problem/Question/Abstract:

This article gives you two routines allowing for fast encoding and decoding in and out of the MIME format.

Answer:

I have written the following unit to replace the INDY TIdEncoderMIME and TIdDecoderMIME components. This "Codec" is used in Email-Software, primarely.

First reason was the lack of speed of these components. Second reason was, that they are components and therefore require the VCL - an heavy extra load on otherwise nonVCL systems.

Both routines are written in Assembler and overloaded by different versions allowing for easy access.

I am sure, some of your are able to increase the speed even some more. Please let me know. Thanks.

I have introduced a compiler switch to switch between a fast decoding mode and a more secure decoding mode. It is up to you, which you like to use. I recomend using the more secure mode, especially if the user is required to work with the encoded data.

{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Unit Name : uBase64Codec
* Author    : Daniel Wischnewski
* Copyright : Copyright &copy; 2001-2003 by gate(n)etwork GmbH. All Rights Reserved.
* Creator   : Daniel Wischnewski
* Contact   : Daniel Wischnewski (e-mail: delphi3000(at)wischnewski.tv);
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}

//                               * * * License * * *
//
// The contents of this file are used with permission, subject to the Mozilla
// Public License Version 1.1 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
//                       http://www.mozilla.org/MPL/MPL-1.1.html
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or  implied. See the License for
// the specific language governing rights and limitations under the License.
//

//                               * * * My Wish * * *
//
// If you come to use this unit for your work, I would like to know about it.
// Drop me an e-mail and let me know how it worked out for you. If you wish, you
// can send me a copy of your work. No obligations!
// My e-mail address: delphi3000(at)wischnewski.tv
//

//                               * * * History * * *
//
// Version 1.0 (Oct-10 2002)
//    first published on Delphi-PRAXiS (www.delphipraxis.net)
//
// Version 1.1 (May-13 2003)
//    introduced a compiler switch (SpeedDecode) to switch between a faster
//    decoding variant (prior version) and a litte less fast, but secure variant
//    to work around bad formatted data (decoding only!)
//

unit Base64;

interface

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !! THE COMPILER SWITCH MAY BE USED TO ADJUST THE BEHAVIOR !!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

// enable "SpeedDecode"
//     the switch to gain speed while decoding the message, however, the codec
//     will raise different exceptions/access violations or invalid output if
//     the incoming data is invalid or missized.

// disable "SpeedDecode"
//     the switch to enable a data check, that will scan the data to decode to
//     be valid. This method is to be used if you cannot guarantee to validity
//     of the data to be decoded.

{.DEFINE SpeedDecode}

{$IFNDEF SpeedDecode}
{$DEFINE ValidityCheck}
{$ENDIF}

uses SysUtils;

// codiert einen String in die zugeh�rige Base64-Darstellung
function Base64Encode(const InText: AnsiString): AnsiString; overload;
// decodiert die Base64-Darstellung eines Strings in den zugeh�rigen String
function Base64Decode(const InText: AnsiString): AnsiString; overload;

// bestimmt die Gr��e der Base64-Darstellung
function CalcEncodedSize(InSize: Cardinal): Cardinal;
// bestimmt die Gr��e der bin�ren Darstellung
function CalcDecodedSize(const InBuffer; InSize: Cardinal): Cardinal;

// codiert einen Buffer in die zugeh�rige Base64-Darstellung
procedure Base64Encode(const InBuffer; InSize: Cardinal; var OutBuffer); overload;
  register;
// decodiert die Base64-Darstellung in einen Buffer
{$IFDEF SpeedDecode}
procedure Base64Decode(const InBuffer; InSize: Cardinal; var OutBuffer); overload;
  register;
{$ENDIF}
{$IFDEF ValidityCheck}
function Base64Decode(const InBuffer; InSize: Cardinal; var OutBuffer): Boolean;
  overload; register;
{$ENDIF}

// codiert einen String in die zugeh�rige Base64-Darstellung
procedure Base64Encode(const InText: PAnsiChar; var OutText: PAnsiChar); overload;
// decodiert die Base64-Darstellung eines Strings in den zugeh�rigen String
procedure Base64Decode(const InText: PAnsiChar; var OutText: PAnsiChar); overload;

// codiert einen String in die zugeh�rige Base64-Darstellung
procedure Base64Encode(const InText: AnsiString; var OutText: AnsiString); overload;
// decodiert die Base64-Darstellung eines Strings in den zugeh�rigen String
procedure Base64Decode(const InText: AnsiString; var OutText: AnsiString); overload;

implementation

const
  cBase64Codec: array[0..63] of AnsiChar =
  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  Base64Filler = '=';

function Base64Encode(const InText: string): string; overload;
begin
  Base64Encode(InText, Result);
end;

function Base64Decode(const InText: string): string; overload;
begin
  Base64Decode(InText, Result);
end;

function CalcEncodedSize(InSize: Cardinal): Cardinal;
begin
  // no buffers passed along, calculate outbuffer size needed
  Result := (InSize div 3) shl 2;
  if ((InSize mod 3) > 0) then
    Inc(Result, 4);
end;

function CalcDecodedSize(const InBuffer; InSize: Cardinal): Cardinal;
type
  BA = array of Byte;
begin
  Result := 0;
  if InSize = 0 then
    Exit;
  if InSize mod 4 <> 0 then
    Exit;
  Result := InSize div 4 * 3;
  if (BA(InBuffer)[InSize - 2] = Ord(Base64Filler)) then
    Dec(Result, 2)
  else if BA(InBuffer)[InSize - 1] = Ord(Base64Filler) then
    Dec(Result);
end;

procedure Base64Encode(const InBuffer; InSize: Cardinal; var OutBuffer
  ); register;
var
  ByThrees, LeftOver: Cardinal;
  // reset in- and outbytes positions
asm
  // load addresses for source and destination
  // PBYTE(InBuffer);
  mov  ESI, [EAX]
  // PBYTE(OutBuffer);
  mov  EDI, [ECX]
  // ByThrees := InSize div 3;
  // LeftOver := InSize mod 3;
  // load InSize (stored in EBX)
  mov  EAX, EBX
  // load 3
  mov  ECX, $03
  // clear upper 32 bits
  xor  EDX, EDX
  // divide by ECX
  div  ECX
  // save result
  mov  ByThrees, EAX
  // save remainder
  mov  LeftOver, EDX
  // load addresses
  lea  ECX, cBase64Codec[0]
  // while I < ByThrees do
  // begin
  xor  EAX, EAX
  xor  EBX, EBX
  xor  EDX, EDX
  cmp  ByThrees, 0
  jz   @@LeftOver
  @@LoopStart:
    // load the first two bytes of the source triplet
    LODSW
    // write Bits 0..5 to destination
    mov  BL, AL
    shr  BL, 2
    mov  DL, BYTE PTR [ECX + EBX]
    // save the Bits 12..15 for later use [1]
    mov  BH, AH
    and  BH, $0F
    // save Bits 6..11
    rol  AX, 4
    and  AX, $3F
    mov  DH, BYTE PTR [ECX + EAX]
    mov  AX, DX
    // store the first two bytes of the destination quadruple
    STOSW
    // laod last byte (Bits 16..23) of the source triplet
    LODSB
    // extend bits 12..15 [1] with Bits 16..17 and save them
    mov  BL, AL
    shr  BX, 6
    mov  DL, BYTE PTR [ECX + EBX]
    // save bits 18..23
    and  AL, $3F
    xor  AH, AH
    mov  DH, BYTE PTR [ECX + EAX]
    mov  AX, DX
    // store the last two bytes of the destination quadruple
    STOSW
    dec  ByThrees
  jnz  @@LoopStart
  @@LeftOver:
  // there are up to two more bytes to encode
  cmp  LeftOver, 0
  jz   @@Done
  // clear result
  xor  EAX, EAX
  xor  EBX, EBX
  xor  EDX, EDX
  // get left over 1
  LODSB
  // load the first six bits
  shl  AX, 6
  mov  BL, AH
  // save them
  mov  DL, BYTE PTR [ECX + EBX]
  // another byte ?
  dec  LeftOver
  jz   @@SaveOne
  // save remaining two bits
  shl  AX, 2
  and  AH, $03
  // get left over 2
  LODSB
  // load next 4 bits
  shl  AX, 4
  mov  BL, AH
  // save all 6 bits
  mov  DH, BYTE PTR [ECX + EBX]
  shl  EDX, 16
  // save last 4 bits
  shr  AL, 2
  mov  BL, AL
  // save them
  mov  DL, BYTE PTR [ECX + EBX]
  // load base 64 'no more data flag'
  mov  DH, Base64Filler
  jmp  @@WriteLast4
  @@SaveOne:
  // adjust the last two bits
  shr  AL, 2
  mov  BL, AL
  // save them
  mov  DH, BYTE PTR [ECX + EBX]
  shl  EDX, 16
  // load base 64 'no more data flags'
  mov  DH, Base64Filler
  mov  DL, Base64Filler
  // ignore jump, as jump reference is next line !
  // jmp  @@WriteLast4
  @@WriteLast4:
    // load and adjust result
    mov  EAX, EDX
    ror EAX, 16
    // save it to destination
    STOSD
  @@Done:
end;

{$IFDEF SpeedDecode}

procedure Base64Decode(const InBuffer; InSize: Cardinal; var OutBuffer);
  overload; register;
{$ENDIF}
{$IFDEF ValidityCheck}
  function Base64Decode(const InBuffer; InSize: Cardinal; var OutBuffer):
      Boolean; overload; register;
  {$ENDIF}
  const
  {$IFDEF SpeedDecode}
    cBase64Codec: array[0..127] of Byte =
  {$ENDIF}
  {$IFDEF ValidityCheck}
    cBase64Codec: array[0..255] of Byte =
  {$ENDIF}
    (
      $FF, $FF, $FF, $FF, $FF, {005>} $FF, $FF, $FF, $FF, $FF, // 000..009
      $FF, $FF, $FF, $FF, $FF, {015>} $FF, $FF, $FF, $FF, $FF, // 010..019
      $FF, $FF, $FF, $FF, $FF, {025>} $FF, $FF, $FF, $FF, $FF, // 020..029
      $FF, $FF, $FF, $FF, $FF, {035>} $FF, $FF, $FF, $FF, $FF, // 030..039
      $FF, $FF, $FF, $3E, $FF, {045>} $FF, $FF, $3F, $34, $35, // 040..049
      $36, $37, $38, $39, $3A, {055>} $3B, $3C, $3D, $FF, $FF, // 050..059
      $FF, $FF, $FF, $FF, $FF, {065>} $00, $01, $02, $03, $04, // 060..069
      $05, $06, $07, $08, $09, {075>} $0A, $0B, $0C, $0D, $0E, // 070..079
      $0F, $10, $11, $12, $13, {085>} $14, $15, $16, $17, $18, // 080..089
      $19, $FF, $FF, $FF, $FF, {095>} $FF, $FF, $1A, $1B, $1C, // 090..099
      $1D, $1E, $1F, $20, $21, {105>} $22, $23, $24, $25, $26, // 100..109
      $27, $28, $29, $2A, $2B, {115>} $2C, $2D, $2E, $2F, $30, // 110..119
      $31, $32, $33, $FF, $FF, {125>} $FF, $FF, $FF // 120..127

  {$IFDEF ValidityCheck}
      {125>}, $FF, $FF, // 128..129
      $FF, $FF, $FF, $FF, $FF, {135>} $FF, $FF, $FF, $FF, $FF, // 130..139
      $FF, $FF, $FF, $FF, $FF, {145>} $FF, $FF, $FF, $FF, $FF, // 140..149
      $FF, $FF, $FF, $FF, $FF, {155>} $FF, $FF, $FF, $FF, $FF, // 150..159
      $FF, $FF, $FF, $FF, $FF, {165>} $FF, $FF, $FF, $FF, $FF, // 160..169
      $FF, $FF, $FF, $FF, $FF, {175>} $FF, $FF, $FF, $FF, $FF, // 170..179
      $FF, $FF, $FF, $FF, $FF, {185>} $FF, $FF, $FF, $FF, $FF, // 180..189
      $FF, $FF, $FF, $FF, $FF, {195>} $FF, $FF, $FF, $FF, $FF, // 190..199
      $FF, $FF, $FF, $FF, $FF, {205>} $FF, $FF, $FF, $FF, $FF, // 200..209
      $FF, $FF, $FF, $FF, $FF, {215>} $FF, $FF, $FF, $FF, $FF, // 210..219
      $FF, $FF, $FF, $FF, $FF, {225>} $FF, $FF, $FF, $FF, $FF, // 220..229
      $FF, $FF, $FF, $FF, $FF, {235>} $FF, $FF, $FF, $FF, $FF, // 230..239
      $FF, $FF, $FF, $FF, $FF, {245>} $FF, $FF, $FF, $FF, $FF, // 240..249
      $FF, $FF, $FF, $FF, $FF, {255>} $FF // 250..255
  {$ENDIF}
      );
  asm
  push EBX
  mov  ESI, [EAX]
  mov  EDI, [ECX]
  {$IFDEF ValidityCheck}
    mov  EAX, InSize
    and  EAX, $03
    cmp  EAX, $00
    jz   @@DecodeStart
    jmp  @@ErrorDone
    @@DecodeStart:
  {$ENDIF}
  mov  EAX, InSize
  shr  EAX, 2
  jz   @@Done
  lea  ECX, cBase64Codec[0]
  xor  EBX, EBX
  dec  EAX
  jz   @@LeftOver
  push EBP
  mov  EBP, EAX
  @@LoopStart:
    // load four bytes into EAX
    LODSD
    // save them to EDX as AX is used to store results
    mov  EDX, EAX
    // get bits 0..5
    mov  BL, DL
    // decode
    mov  AH, BYTE PTR [ECX + EBX]
    {$IFDEF ValidityCheck}
      // check valid code
      cmp  AH, $FF
      jz   @@ErrorDoneAndPopEBP
    {$ENDIF}
    // get bits 6..11
    mov  BL, DH
    // decode
    mov  AL, BYTE PTR [ECX + EBX]
    {$IFDEF ValidityCheck}
      // check valid code
      cmp  AL, $FF
      jz   @@ErrorDoneAndPopEBP
    {$ENDIF}
    // align last 6 bits
    shl  AL, 2
    // get first 8 bits
    ror  AX, 6
    // store first byte
    STOSB
    // align remaining 4 bits
    shr  AX, 12
    // get next two bytes from source quad
    shr  EDX, 16
    // load bits 12..17
    mov  BL, DL
    // decode
    mov  AH, BYTE PTR [ECX + EBX]
    {$IFDEF ValidityCheck}
      // check valid code
      cmp  AH, $FF
      jz   @@ErrorDoneAndPopEBP
    {$ENDIF}
    // align ...
    shl  AH, 2
    // ... and adjust
    rol  AX, 4
    // get last bits 18..23
    mov  BL, DH
    // decord
    mov  BL, BYTE PTR [ECX + EBX]
    {$IFDEF ValidityCheck}
      // check valid code
      cmp  BL, $FF
      jz   @@ErrorDoneAndPopEBP
    {$ENDIF}
    // enter in destination word
    or   AH, BL
    // and store to destination
    STOSW
    // more coming ?
    dec  EBP
  jnz  @@LoopStart
  pop  EBP
  // no
  // last four bytes are handled separately, as special checking is needed
  // on the last two bytes (may be end of data signals '=' or '==')
  @@LeftOver:
  // get the last four bytes
  LODSD
  // save them to EDX as AX is used to store results
  mov  EDX, EAX
  // get bits 0..5
  mov  BL, DL
  // decode
  mov  AH, BYTE PTR [ECX + EBX]
  {$IFDEF ValidityCheck}
    // check valid code
    cmp  AH, $FF
    jz   @@ErrorDone
  {$ENDIF}
  // get bits 6..11
  mov  BL, DH
  // decode
  mov  AL, BYTE PTR [ECX + EBX]
  {$IFDEF ValidityCheck}
    // check valid code
    cmp  AL, $FF
    jz   @@ErrorDone
  {$ENDIF}
  // align last 6 bits
  shl  AL, 2
  // get first 8 bits
  ror  AX, 6
  // store first byte
  STOSB
  // get next two bytes from source quad
  shr  EDX, 16
  // check DL for "end of data signal"
  cmp  DL, Base64Filler
  jz   @@SuccessDone
  // align remaining 4 bits
  shr  AX, 12
  // load bits 12..17
  mov  BL, DL
  // decode
  mov  AH, BYTE PTR [ECX + EBX]
  {$IFDEF ValidityCheck}
    // check valid code
    cmp  AH, $FF
    jz   @@ErrorDone
  {$ENDIF}
  // align ...
  shl  AH, 2
  // ... and adjust
  rol  AX, 4
  // store second byte
  STOSB
  // check DH for "end of data signal"
  cmp  DH, Base64Filler
  jz   @@SuccessDone
  // get last bits 18..23
  mov  BL, DH
  // decord
  mov  BL, BYTE PTR [ECX + EBX]
  {$IFDEF ValidityCheck}
    // check valid code
    cmp  BL, $FF
    jz   @@ErrorDone
  {$ENDIF}
  // enter in destination word
  or   AH, BL
  // AH - AL for saving last byte
  mov  AL, AH
  // store third byte
  STOSB
  @@SuccessDone:
  {$IFDEF ValidityCheck}
    mov  Result, $01
    jmp  @@Done
    @@ErrorDoneAndPopEBP:
    pop  EBP
    @@ErrorDone:
    mov  Result, $00
  {$ENDIF}
  @@Done:
  pop  EBX
  end;

  procedure Base64Encode(const InText: PAnsiChar; var OutText: PAnsiChar);
  var
    InSize, OutSize: Cardinal;
  begin
    // get size of source
    InSize := Length(InText);
    // calculate size for destination
    OutSize := CalcEncodedSize(InSize);
    // reserve memory
    OutText := StrAlloc(Succ(OutSize));
    OutText[OutSize] := #0;
    // encode !
    Base64Encode(InText, InSize, OutText);
  end;

  procedure Base64Encode(const InText: AnsiString; var OutText: AnsiString);
    overload;
  var
    InSize, OutSize: Cardinal;
    PIn, POut: Pointer;
  begin
    // get size of source
    InSize := Length(InText);
    // calculate size for destination
    OutSize := CalcEncodedSize(InSize);
    // prepare string length to fit result data
    SetLength(OutText, OutSize);
    PIn := @InText[1];
    POut := @OutText[1];
    // encode !
    Base64Encode(PIn, InSize, POut);
  end;

  procedure Base64Decode(const InText: PAnsiChar; var OutText: PAnsiChar);
    overload;
  var
    InSize, OutSize: Cardinal;
  begin
    // get size of source
    InSize := Length(InText);
    // calculate size for destination
    OutSize := CalcDecodedSize(InText, InSize);
    // reserve memory
    OutText := StrAlloc(Succ(OutSize));
    OutText[OutSize] := #0;
    // encode !
{$IFDEF SpeedDecode}
    Base64Decode(InText, InSize, OutText);
{$ENDIF}
{$IFDEF ValidityCheck}
    if not Base64Decode(InText, InSize, OutText) then
      OutText[0] := #0;
{$ENDIF}
  end;

  procedure Base64Decode(const InText: AnsiString; var OutText: AnsiString);
    overload;
  var
    InSize, OutSize: Cardinal;
    PIn, POut: Pointer;
  begin
    // get size of source
    InSize := Length(InText);
    // calculate size for destination
    PIn := @InText[1];
    OutSize := CalcDecodedSize(PIn, InSize);
    // prepare string length to fit result data
    SetLength(OutText, OutSize);
    FillChar(OutText[1], OutSize, '.');
    POut := @OutText[1];
    // encode !
{$IFDEF SpeedDecode}
    Base64Decode(PIn, InSize, POut);
{$ENDIF}
{$IFDEF ValidityCheck}
    if not Base64Decode(PIn, InSize, POut) then
      SetLength(OutText, 0);
{$ENDIF}
  end;

end.

2004. június 13., vasárnap

Check for a duplicate key index programmatically


Problem/Question/Abstract:

I have a DBISAM 2.04 table with several indexes. It actually lists project details. One field is the ProjectNo (a text field some 20 char wide). I want to make sure that the same PropjectNo is not entered twice. I could make the index unique, and that would no doubt work. But the error message returned in not very user friendly - I would rather trap it myself. I assume that in the OnBeforEInsert event I would have some code that checks to see if this index key already exists. If so, then I warn the user (perhaps even allowing the record to be saved if the user insists). And then aborting the save if a duplicate. How do I find an existing key, i.e. something like KeyExists(['99023']) ? Would I have to do a Locate or something?

Answer:

Make a generic function like:

function TMyForm.CheckDuplicateKey(ATable: string; const Field: TField): Boolean;
var
  cSQL, KeyField, cValue: string;
begin
  KeyField := Field.FieldName;
  cValue := Field.AsString;
  cSQL := Format('select %s from %s where %s = %s', [KeyField, ATable, KeyField,
    cValue]);
  with LookupQuery do
  begin
    SQL.Clear;
    SQL.Add(cSQL);
    Open;
    if RecordCount > 0 then
      Result := True
    else
      Result := False;
    Close;
  end;
end;

and use it in your key field's OnValidate handler like:

procedure TMyForm.MainQueryMyIDValidate(Sender: TField);
begin
  if CheckDuplicateKey('MyTable', Sender) then
    raise Exception.Create('The table already has a record with this key.');
end;

2004. június 12., szombat

Retrieve the password of a protected access database


Problem/Question/Abstract:

The password of an access database can easily be retrieved using the function below

Answer:

I know there that there are many utilities out there costing $$ for removing the password of an access database. Here's how to implement it in Delphi.Please note that this method is not meant for a database with user-level security and work group information file. The idea is based on the file format of an access db.

The password is stored from location $42 and encrypted using simple xoring. The following function does decryption.

function GetPassword(filename: string): string;
var
  Stream: TFilestream;
  buffer: array[0..12] of char;
  str: string;
begin
  try
    stream := TFileStream.Create(filename, fmOpenRead);
  except
    ShowMessage('Could not open the file.Make sure that the file is not in use.');
    exit;
  end;
  stream.Seek($42, soFromBeginning);
  stream.Read(buffer, 13);
  stream.Destroy;

  str := chr(Ord(buffer[0]) xor $86);
  str := str + chr(Ord(buffer[1]) xor $FB);
  str := str + chr(Ord(buffer[2]) xor $EC);
  str := str + chr(Ord(buffer[3]) xor $37);
  str := str + chr(Ord(buffer[4]) xor $5D);
  str := str + chr(Ord(buffer[5]) xor $44);
  str := str + chr(Ord(buffer[6]) xor $9C);
  str := str + chr(Ord(buffer[7]) xor $FA);
  str := str + chr(Ord(buffer[8]) xor $C6);
  str := str + chr(Ord(buffer[9]) xor $5E);
  str := str + chr(Ord(buffer[10]) xor $28);
  str := str + chr(Ord(buffer[11]) xor $E6);
  str := str + chr(Ord(buffer[12]) xor $13);
  Result := str;
end;

2004. június 11., péntek

Better way to display [error] messages


Problem/Question/Abstract:

Better way to display [error] messages

Answer:

If you display more than a few [error] messages in your application, using a simple method such as the following may not be the best approach:

Application.MessageBox('File not found', 'Error', mb_OK);

Above method of displaying errors will make it harder to modify actual messages since they are distributed all over your application source code. It may be better to have a "centralized" function that can display error messages, or better yet, a centralized function that can display replaceable error messages. Consider the following example:

type
  cnMessageIDs =
    (
    nMsgID_NoError,
    nMsgID_FileNotFound,
    nMsgID_OutOfMemory,
    nMsgID_ExitProgram
    // list your other error
    // IDs here...
    );

const
  csMessages_ShortVersion: array[Low(cnMessageIDs)..High(cnMessageIDs)] of PChar =
  (
    'No error',
    'File not found',
    'Out of memory',
    'Exit program?'
    // other error messages...
    );

  csMessages_DetailedVersion: array[Low(cnMessageIDs)..High(cnMessageIDs)]
  of PChar =
    (
    'No error; please ignore!',

    'File c:\config.sys not found.' +
    'Contact your sys. admin.',

    'Out of memory. You need ' +
    'at least 4M for this function',

    'Exit program? ' +
    'Save your data first!'
    // other error messages...
    );

procedure MsgDisplay(
  cnMessageID: cnMessageIDs);
begin
  // set this to False to display
  // short version of the messages
  if (True) then
    Application.MessageBox(csMessages_DetailedVersion[cnMessageID], 'Error', mb_OK)
  else
    Application.MessageBox(csMessages_ShortVersion[cnMessageID], 'Error', mb_OK);
end;

Now, whenever you want to display an error message, you can call the MsgDisplay() function with the message ID rather than typing the message itself:

MsgDisplay(nMsgID_FileNotFound);

MsgDisplay() function will not only let you keep all your error messages in one place -- inside one unit for example, but it will also let you keep different sets of error messages -- novice/expert, debug/release, and even different sets for different languages.

2004. június 10., csütörtök

Function to Populate a column of the DBGrid PickList so as to facilitate easy data entry in a grid


Problem/Question/Abstract:

A function to populate the DBGrid PickList to have auto selection of added field value when the grid is used to display a table

Answer:

The PickList of a DBGrid can be made useful for data entry through a dbgrid. This can be accomplished by the following function.Whenever a new entry is added to a particular field, that too can be made to appear in the picklist with the function given below.The PopulatePickList function can be called within DataSource.OnDataChange event so that it gets updated whenever a new entry is added.

procedure PopulatePickList(Column: TColumn; Table: TTable; FieldName: string);
var
  QryTemp: TQuery;
  i: integer;
begin
  Column.PickList.Clear;
  QryTemp := TQuery.Create(nil);
  with QryTemp do
  begin
    DatabaseName := Table.DatabaseName;
    SQL.Clear;
    SQL.Add('SELECT DISTINCT ' + FieldName + ' from ' + Table.TableName);
  end;

  with QryTemp do
  begin
    Active := True;
    First;
    for i := 0 to QryTemp.RecordCount - 1 do
    begin
      if FieldByName(FieldName).AsString <> '' then
        Column.PickList.Add(FieldByName(FieldName).AsString);
      Next;
    end;
    Active := False;
  end;
  QryTemp.Free;
end;

procedure TForm1.DataSourceDataChange(Sender: TObject; Field: TField);
begin
  PopulatePickList(DBGrid.Columns[2], Table, 'Field');
  //replace table with your tableName of the grid
  //DBGrid.Columns[2] with your DBGrid Column that you want the PickList for
  //Field with the field for the PickList
end;

2004. június 9., szerda

Track the mouse position over a TPanel on a form


Problem/Question/Abstract:

I want to track the position of the mouse over a TPanel within the client area of my main form. Using WM_MOUSEMOVE, I can track the mouse position over the main form easily enough, but once the mouse moves over my panel, the tracking stops. What do I need to do to track the position of the mouse over the panel?

Answer:

This is happening because TPanel is a different window with a handle of its own. You need to intercept the WM_MOUSEMOVE message in the TPanels WindowProc procedure. Assuming the form is TForm1 and the panel is Panel1:

First declare the following in the forms class:

private
{ Private declarations }
OldPanelWndProc: TWndMethod;

procedure NewPanelWndProc(var Message: TMessage);

Finally, implement the relevant code. Note how you should always call the old WindowProc procedure after you've handled the message. Also, WindowProc should be restored to it's original procedure when the form (containing the panel) is hidden. It would be a bad idea to restore the WindowProc procedure in the forms OnDestroy event because if it (the form) is hidden and shown again, it's going to cause problems with WindowProc being reassigned when it shouldn't be.

procedure TForm1.FormShow(Sender: TObject);
begin
  OldPanelWndProc := Panel1.WindowProc;
  Panel1.WindowProc := NewPanelWndProc;
end;

procedure TForm1.FormHide(Sender: TObject);
begin
  Panel1.WindowProc := OldPanelWndProc;
end;

procedure TForm1.NewPanelWndProc(var Message: TMessage);
begin
  case Message.Msg of
    WM_MOUSEMOVE:
      Caption := 'x = ' + inttostr(Message.LParamLo) + ' y = ' +
                         inttostr(Message.LParamHi);
  end;
  OldPanelWndProc(Message);
end;

2004. június 8., kedd

Managing a Single Instance of a Non-Modal Form


Problem/Question/Abstract:

How to manage the application's non-modal forms properly - to make sure that only one instance of a form is present at any given time, like it is done automatically for modal forms?

Answer:

When you have a modal form, you create, display and destroy it usually in a single uninterrupted sequence of code instructions, therefore it is easy to ensure that your form variable is equal to NIL after the form is expired, so you easily eliminate the risk of creating the same form twice or, even worse, attempting to access non-existing form when the only form's remains you actually have is the form variable with non-NIL value in it.

The problem with non-modal forms is that you usually create and display them in one place, then do whatever you want with your application (and not only that form), and order them to destroy themselves when they are no longer needed at any time - you cannot say beforehand where and when that will happen.
It is natural to close and free such a non-modal form from itself, but where to put clean-up instructions then? Without them, the application cannot know whether the form is alive - it relies merely on the form variable value (is it equal to NIL?) to determine if the form is still around. It is possible to introduce some application-level flags to keep track of the forms presence, but it is not an elegant solution.

Fortunately, as almost always with Delphi, there is a clear way to solve the problem.

Suppose you have frmNonModal as a form variable of TfrmNonModal class.

The procedure is simple:

   1. Add the following OnDestroy event handler to the form:

procedure TfrmNonModal.FormDestroy(Sender: TObject);
begin
  frmNonModal := nil;
  inherited;
end; {TfrmNonModal.FormDestroy}

Note that you cannot substitute frmNonModal with Self, though it seems to be the same from the first glance. The difference is that Self points to the object itself (and we don't want to nullify it prematurely), and frmNonModal is just an external (to the object) variable, which points to the object. By setting this variable to NIL we do not affect any internal functionality of the object, but rather just disconnect its link to the outer world. In our case this is exactly what we need, as we plan to check this variable when creating the form, as shown below.  

   2. Add the following OnClose event handler to the form:

procedure TfrmNonModal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  inherited;
  Action := caFree;
end; {TfrmNonModal.FormClose}

This is needed to instruct our form to free itself when we close it. Note that by default Action is caHide, i.e. your form is just being closed (hidden), but not destroyed after calling TForm.Close.
  
   3. Bring your form to life as follows, for example in the menu item's OnClick event handler on your main form (of TfrmMain class):

procedure TfrmMain.itmNonModalFormClick(Sender: TObject);
begin
  if Assigned(frmNonModal) then
  begin
    {if the form already exists, just bring it to the front}
    frmNonModal.Show;
    frmNonModal.WindowState := wsNormal;
    frmNonModal.BringToFront;
  end
  else
  begin
    {create the form if it does not exist}
    frmNonModal := TfrmNonModal.Create(Application);
    try
      {display as non-modal form}
      frmNonModal.Show;
    except
      {clean up the form and form variable if unsuccessful}
      FreeAndNil(frmNonModal);
    end; {try}
  end; {if}
end; {TfrmMain.itmNonModalFormClick}

That's it. Now your application always knows whether your non-modal form is present (created), and manages to allow not more than a single instance of such form at a time.

2004. június 7., hétfő

How to resize open forms automatically when the Desktop size changes


Problem/Question/Abstract:

I have created a form which is snapped to the top of the screen. When I change the size of the Windows Desktop, the visible form isn't resized accordingly.

Answer:

I use the following code and it works quite good, even if the desktop size is changed:

type
  TForm1 = class(TForm)
  private
    procedure WMWindowPosChanging(var Message: TWMWindowPosMsg);
      message WM_WINDOWPOSCHANGING;

    { ... }

implementation

{ ... }

var
  WorkAreaRect: TRect;
  NewWorkAreaFlag: Boolean;

  { ... }

procedure TForm1.WMWindowPosChanging(var Message: TWMWindowPosMsg);
begin
  if (WindowState <> wsMaximized) then
  begin
    if (Message.WindowPos.Flags and SWP_NOMOVE) = 0 then
    begin {form is moved}
      if NewWorkAreaFlag then
      begin {workarea might have changed since last call}
        SystemParametersInfo(SPI_GETWORKAREA, 0, @WorkAreaRect, 0);
      end;
      {snap form to border here, something
                        like Message.WindowPos.X := WorkAreaRect.Left if near to left border}
      { ... }
    end;
    NewWorkAreaFlag := ((Message.WindowPos.Flags and (SWP_NOMOVE or SWP_NOSIZE)) <>
      0);
    {True if form was (probably) dropped => get workarea again}
  end;
end;

{ ... }

initialization
  NewWorkAreaFlag := True;

2004. június 6., vasárnap

Splitting a string in a string list


Problem/Question/Abstract:

A function that splits a string in parts separated by a substring and returns the parts in a StringList

Answer:

Solve 1:

The following functions split a string in parts separated by a substring and return the parts in a string list that may be passed as third parameter or created by the function (and in this latter case it must be freed by the caller):

interface

uses classes;

function SplitStrings(const str: string;
  const separator: string = ',';
  Strings: TStrings = nil): TStrings;
function AnsiSplitStrings(const str: string;
  const separator: string = ',';
  Strings: TStrings = nil): TStrings;

implementation

uses sysutils;

function SplitStrings(const str: string; const separator: string;
  Strings: TStrings): TStrings;
// Fills a string list with the parts of "str" separated by
// "separator". If Nil is passed instead of a string list,
// the function creates a TStringList object which has to
// be freed by the caller
var
  n: integer;
  p, q, s: PChar;
  item: string;
begin
  if Strings = nil then
    Result := TStringList.Create
  else
    Result := Strings;
  try
    p := PChar(str);
    s := PChar(separator);
    n := Length(separator);
    repeat
      q := StrPos(p, s);
      if q = nil then
        q := StrScan(p, #0);
      SetString(item, p, q - p);
      Result.Add(item);
      p := q + n;
    until q^ = #0;
  except
    item := '';
    if Strings = nil then
      Result.Free;
    raise;
  end;
end;

function AnsiSplitStrings(const str: string; const separator: string;
  Strings: TStrings): TStrings;
// Fills a string list with the parts of "str" separated by
// "separator". If Nil is passed instead of a string list,
// the function creates a TStringList object which has to
// be freed by the caller
// ANSI version
var
  n: integer;
  p, q, s: PChar;
  item: string;
begin
  if Strings = nil then
    Result := TStringList.Create
  else
    Result := Strings;
  try
    p := PChar(str);
    s := PChar(separator);
    n := Length(separator);
    repeat
      q := AnsiStrPos(p, s);
      if q = nil then
        q := AnsiStrScan(p, #0);
      SetString(item, p, q - p);
      Result.Add(item);
      p := q + n;
    until q^ = #0;
  except
    item := '';
    if Strings = nil then
      Result.Free;
    raise;
  end;
end;

Examples:

procedure TForm1.Button1Click(Sender: TObject);
begin
  SplitStrings(Edit1.Text, ', ', ListBox1.Items);
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  Parts: TStrings;
begin
  Parts := nil;
  try
    Parts := SplitStrings(Edit1.Text, ', ');
    ShowMessage('First part is "' + Parts[0] + '"');
  finally
    Parts.Free;
  end;
end;

You can see an example using a dynamic array instead of a StringList in a separate article "Splitting a string in an dynamic array".


Solve 2:

Shorten way:

function SplitStrings(const str: string; const separator: string;
  Strings: TStrings): TStrings;
// Fills a string list with the parts of "str" separated by
// "separator". If Nil is passed instead of a string list,
// the function creates a TStringList object which has to
// be freed by the caller
begin
  if Strings = nil then
    Result := TStringList.Create
  else
    Result := Strings;

  //This replaces the separators in str with CRLF so as to fit the format  of a stringlist.
  Result.Text := StringReplace(str, separator, #13#10, [rfReplaceAll]);
end;

2004. június 5., szombat

How to read the color of a pixel


Problem/Question/Abstract:

I need to determine if certain portions of my canvas are black. While this seemed easy enough at first, I'm at a roadblock trying to determine pixel color. As I usually do, I wrote a little test program and painted a certain area black. I tried the following code to read a pixel in that area:

if Canvas.Pixels[444, 399] = clBlack then
  MessageBeep(mb_ok);

I never get the beep. What am I doing wrong, and what would be the correct way to do this.

Answer:

Are you shure you hit the right pixel ? Try


canvas.pixels[444, 399] = clBlack
if canvas.pixels[444, 399] = clBlack then
  MessageBeep(mb_ok);


Windows converts colors (at least if you are using less than 24 bit screen mode). But black should exists on all palettes, I think. The color value of a pixel will be a DWORD (32 bit), encoded like this:

$XXRRGGBB

where XX are return values (as far as I remember, it even tells you , if it had to convert a color here). So you could try something like

(color and $FFFFFF) = clBlack

to get the return value out or

= $000000

to be sure it not depends on clBlack .

If that doesn't work, let it write the pixel color to screen an compare to value of clBlack. If worst case , get R,G and B and check if (near to ) 0.

2004. június 4., péntek

Disable a form movement


Problem/Question/Abstract:

How can I disable the any form movement?

Answer:

Always I saw a question: how can I move a window by hit in any part of form?
But I never saw a reverse question: how to disable a movement.

type
  TyourForm = class(TForm)
  private
    { Private declarations }
    procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
  end;

procedure TyourForm.WMNCHitTest(var Message: TWMNCHitTest);
begin
  inherited;

  with Message do
    if Result = HTCAPTION then
      Result := HTNOWHERE;
end;

2004. június 3., csütörtök

Retrieve just 1 row from a table (SQL)


Problem/Question/Abstract:

How do i retrive just 1 row from a sql table

Answer:

found this nice sql-tip for ya::

you have 2 options:

- use TOP function in sql

-----start
SELECT TOP 1 * FROM myTable
-----end

- by setting the rowcount before selecting in sql

-----start
SET ROWCOUNT 1
SELECT * FROM myTable
-----end

Note: If you use SET ROWCOUNT and you have a batch of commands, make sure you SET ROWCOUNT immediately before the SELECT statement. If you SET ROWCOUNT before an UPDATE or DELETE it will limit the number of rows affected by those operations.