2009. március 14., szombat

How to check if a drive is ready


Problem/Question/Abstract:

How can I check if there is a disk in the "A" drive without an error message box telling you that it is not ready?

Answer:

The following function accepts a drive letter as a parameter, and it will return a boolean value that indicates whether or not there is a disk in the drive.


function DiskInDrive(Drive: Char): Boolean;
var
  ErrorMode: word;
begin
  {make it upper case}
  if Drive in ['a'..'z'] then
    Dec(Drive, $20);
  {make sure it's a letter}
  if not (Drive in ['A'..'Z']) then
    raise EConvertError.Create('Not a valid drive ID');
  {turn off critical errors}
  ErrorMode := SetErrorMode(SEM_FailCriticalErrors);
  try
    { drive 1 = a, 2 = b, 3 = c, etc.}
    if DiskSize(Ord(Drive) - $40) = -1 then
      Result := False
    else
      Result := True;
  finally
    {restore old error mode}
    SetErrorMode(ErrorMode);
  end;
end;

2009. március 13., péntek

The future of the BDE


Problem/Question/Abstract:

After Borland's official announcement regarding the future of the BDE, I contacted (and was contacted by) many Delphi developers who are currently using the BDE to learn about their future plans regarding data access...

Answer:

After Borland's official announcement regarding the future of the BDE, I contacted (and was contacted by) many Delphi developers who are currently using the BDE to learn about their future plans regarding data access.

For local databases, the BDE will keep being used, although a discrete minority are seriously considering switching to a BDE alternative in the short term (mainly Interbase accessed thru IBX or dbExpress, and third-party data access components).

For server databases, the scenario changes radically. Among those who are still using previous Delphi versions, many are not likely to upgrade, so they'll keep using the BDE + SQL Links all they can, while almost all the rest are considering mainly dbExpress, ADO and ADO.Net, but developers showed their concern about these alternatives:

dbExpress is not as "universal" as SQL Links, meaning there are missing drivers for some important database servers (like Microsoft SQL Server). About dbExpress being faster than the BDE, this is not true for small queries beause there's no caching mechanism (since there is no front layer like the BDE), so the metadata gets downloaded in every query. I'd like to credit Vasilis Devletoglou for sharing his findings about the inner workings of dbExpress with us. Finally, when one used a technology for many years, sometimes it's a bit difficult not be a bit conservative and consider new technologies as "beta". We all know dbExpress arrived here to stay, but many developers percieve it's still "green" and needs further development.

ADO and ADO.Net don't conform the expectations of Delphi programmers in performance and/or features, and it can't be ignored the fact that most programmers would rather prefer to use a Borland solution.

In conclusion, the only ones that are happy here seem to be those who switched to a BDE alternative some time ago... :-)


Copyright (c) 2001 Ernesto De Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php

2009. március 12., csütörtök

How to create a TPanel with scrollbars


Problem/Question/Abstract:

I want to create a component that has scrollbars (vertical/ horizontal). I tried to get the tricks from TCustomGrid but it doesn't work when I try to set a range/ position value to one of the scrollbars.

Answer:

This example uses an interposer class for convenience (mine, I just wanted to avoid the hassle of creating and installing a proper component for this example) but you should be able to adapt it for a proper component.

{ Example for fitting a panel with scrollbars }

unit Unit1;

interface

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

type
  TPanel = class(Extctrls.TPanel)
  private
    procedure WMVScroll(var msg: TWMSCROLL); message WM_VSCROLL;
    procedure WMHScroll(var msg: TWMSCROLL); message WM_HSCROLL;
    procedure WMGetDlgCode(var msg: TWMGetDlgCode); message WM_GETDLGCODE;
    procedure HandleScrollbar(var msg: TWMSCROLL; bar: Integer);
  protected
    procedure CreateParams(var params: TCreateParams); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure KeyDown(var Key: Word; Shift: TShiftState); override;
  end;

  TForm1 = class(TForm)
    Panel1: TPanel;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

{ TPanel }

procedure TPanel.CreateParams(var params: TCreateParams);
begin
  inherited;
  params.Style := params.Style or WS_VSCROLL or WS_HSCROLL;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  si: TScrollInfo;
begin
  si.cbSize := Sizeof(TScrollInfo);
  si.fMask := SIF_ALL or SIF_DISABLENOSCROLL;
  si.nMin := 0;
  si.nMax := 3 * panel1.clientheight;
  si.nPage := panel1.clientheight div 2;
  si.nPos := 0;
  SetScrollInfo(panel1.handle, SB_VERT, si, true);
  si.nMax := 2 * panel1.clientwidth;
  si.nPage := panel1.clientwidth div 2;
  SetScrollInfo(panel1.handle, SB_HORZ, si, true);
end;

procedure TPanel.HandleScrollbar(var msg: TWMSCROLL; bar: Integer);
var
  si: TScrollInfo;
begin
  msg.result := 0;
  si.cbSize := Sizeof(TscrollInfo);
  si.fMask := SIF_ALL;
  GetScrollInfo(Handle, bar, si);
  si.fMask := SIF_POS;
  { For simplicities sake we use 1/10 of the page size as small scroll
         increment and the page size as large scroll increment }
  case msg.ScrollCode of
    SB_TOP: si.nPos := si.nMin;
    SB_BOTTOM: si.nPos := si.nMax;
    SB_LINEUP: Dec(si.nPos, si.nPage div 10);
    SB_LINEDOWN: Inc(si.nPos, si.nPage div 10);
    SB_PAGEUP: Dec(si.nPos, si.nPage);
    SB_PAGEDOWN: Inc(si.nPos, si.nPage);
    SB_THUMBTRACK, SB_THUMBPOSITION: si.nPos := msg.Pos;
    SB_ENDSCROLL: Exit;
  end;
  si.fMask := SIF_POS;
  if si.nPos < si.nMin then
    si.nPos := si.nMin;
  if si.nPos > si.nMax then
    si.nPos := si.nMax;
  SetScrollInfo(Handle, bar, si, true);
  { Fire a scroll notification off here to allow client to scroll content of panel }
end;

procedure TPanel.KeyDown(var Key: Word; Shift: TShiftState);

  procedure Scroll(scrollcode, message: Cardinal);
  begin
    Perform(message, scrollcode, 0);
  end;

const
  scrollkind: array[Boolean] of Cardinal = (WM_VSCROLL, WM_HSCROLL);
begin
  inherited;
  { Ignoring shift state for arrow keys here for simplicities sake }
  case Key of
    VK_UP: Scroll(SB_LINEUP, WM_VSCROLL);
    VK_LEFT: Scroll(SB_LINEUP, WM_HSCROLL);
    VK_DOWN: Scroll(SB_LINEDOWN, WM_VSCROLL);
    VK_RIGHT: Scroll(SB_LINEDOWN, WM_HSCROLL);
    VK_NEXT: Scroll(SB_PAGEDOWN, scrollkind[ssCtrl in Shift]);
    VK_PRIOR: Scroll(SB_PAGEUP, scrollkind[ssCtrl in Shift]);
    VK_HOME: Scroll(SB_TOP, scrollkind[ssCtrl in Shift]);
    VK_END: Scroll(SB_BOTTOM, scrollkind[ssCtrl in Shift]);
  end;
  Key := 0;
end;

procedure TPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  inherited;
  if (Button = mbLeft) and CanFocus and not Focused then
    SetFocus;
end;

procedure TPanel.WMGetDlgCode(var msg: TWMGetDlgCode);
begin
  msg.result := DLGC_WANTARROWS;
end;

procedure TPanel.WMHScroll(var msg: TWMSCROLL);
begin
  HandleScrollbar(msg, SB_HORZ);
end;

procedure TPanel.WMVScroll(var msg: TWMSCROLL);
begin
  HandleScrollbar(msg, SB_VERT);
end;

end.

2009. március 11., szerda

How to force a form to stay iconized


Problem/Question/Abstract:

How to force a form to stay iconized

Answer:

If your application should be iconized from the beginning, set the for property WindowState to wsMinimized.

To keep a form iconized (and prevent a restore), add the following handler to your form class definition:


// e.g. the private section

procedure WMQueryOpen(var Msg: TWMQueryOpen); message WM_QUERYOPEN;

implementation

// ..

procedure TForm1.WMQueryOpen(var Msg: TWMQueryOpen);
begin
  Msg.Result := 0;
end;

2009. március 10., kedd

Draw a grid on a TPaintBox


Problem/Question/Abstract:

How to draw a grid on a TPaintBox

Answer:

procedure TForm1.DrawPaintBoxGrid(distance: Integer);
var
  xpos, ypos: Integer;
begin
  PaintBox1.Canvas.Brush.Color := clBlack;
  ypos := 0;
  xpos := 0;
  while ypos < PaintBox1.Height do
  begin
    ypos := ypos + distance;
    PaintBox1.Canvas.MoveTo(0, ypos);
    PaintBox1.Canvas.LineTo(PaintBox1.Width, ypos);
    while xpos < PaintBox1.Width do
    begin
      xpos := xpos + distance;
      PaintBox1.Canvas.MoveTo(xpos, 0);
      PaintBox1.Canvas.LineTo(xpos, PaintBox1.Height);
    end;
  end;
end;

2009. március 9., hétfő

Make a TPanel look like the title bar of a window


Problem/Question/Abstract:

I have a good reason why I cannot use forms. So as an alternative I'm using two panels to mimic a simple form, i.e. with no windows icons (close, minimize etc.). One is aligned to the top to pose like the window title bar and the other to client. I want to paint the top panel like a typical title bar. How can I do this?

Answer:

There is an API function named DrawCaption, you can use it to draw the caption bar. Drop a client-aligned TPaintbox on your fake caption panel and do the drawing in the paintboxes OnPaint handler.

procedure TPLabBaseChildform.CaptionPaint(Sender: TObject);
const
  activeFlags: array[Boolean] of DWORD = (0, DC_ACTIVE);
begin
  with Sender as TPaintbox do
    DrawCaption(self.handle, canvas.handle, clientrect, activeFlags[FActive] or
      DC_TEXT or DC_GRADIENT);
end;

To draw other elements as well (beside the icon, which DrawCaption can handle) you use DrawFrameControl instead.

2009. március 8., vasárnap

How to convert the content of a TRichEdit into a bitmap


Problem/Question/Abstract:

Does anyone know of a component or a few lines of code, that could turn the contents of a TRichText field (WIN32 RTF) into a bitmap?

Answer:

Add this in the unit your are developing:


uses
  RichText;

{For this demo add a RichEdit and an Image Control set the RichEdit change event to the lower code}

procedure
  OutputRTFToBmp(RichHolder: TRichEdit; ImageHolder: TBitmap; itemwidth, itemheight: real);
var
  Range: TFormatRange;
  TextBoundary: TRect;
begin
  {Setup the Height and Width of our output}
  ImageHolder.width := round(itemwidth * screen.PixelsPerInch);
  ImageHolder.height := round(itemheight * screen.PixelsPerInch);
  {Set the Size of the Rich Edit}
  textboundary := rect(0, 0, round(itemwidth * 1440), round(itemheight * 1440));
  {Set the Range record}
  range.hdc := ImageHolder.Canvas.handle;
  range.hdctarget := ImageHolder.Canvas.handle;
  range.rc := textboundary;
  range.rcpage := textboundary;
  {Start at character zero}
  range.chrg.cpMin := 0;
  {Display all Characters}
  range.chrg.cpMax := -1;
  {Ask RTF to Draw}
  Sendmessage(RichHolder.handle, EM_FORMATRANGE, 1, longint(@range));
  {Cleanup RTF Cache}
  sendmessage(RichHolder.handle, EM_FORMATRANGE, 0, 0);
end;

procedure TForm1.RichEdit1Change(Sender: TObject);
begin
  OutputRTFToBmp(RichEdit1, Image1.picture.bitmap, 2, 2);
  {Display new stuff, this will flicker so you will have to double buffer}
  image1.refresh;
end;


I use it on Metafiles then you can scale it also.

2009. március 7., szombat

How to do a backward search in a TRichEdit


Problem/Question/Abstract:

How to do a backward search in a TRichEdit

Answer:

Solve 1:

This is how to find text searching backwards:

function FindPreviousInstanceOfSubstring(substr, S: string; startAt: Integer):
  Integer;
var
  i: Integer;
  ch: Char;
begin
  ch := substr[1];
  i := startAt;
  Result := 0; {assume we fail}
  while i >= 1 do
  begin
    if S[i] = ch then
    begin
      if AnsiCompareStr(substr, Copy(S, i, Length(substr))) = 0 then
      begin
        {found an instance}
        Result := i;
        Break;
      end;
    end;
    Dec(i);
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  richedit1.selstart := FindPreviousInstanceOfSubstring
    (edit1.text, richedit1.text, richedit1.gettextlen) - 1;
  richedit1.sellength := Length(edit1.text);
end;


Solve 2:

{Function FindTextBackwards

Parameters:
findWhat: text to find
inString: string to find it in
startAt : character index to start at (1-based)
caseSensitive: determines whether search is case-sensitive
words: if true the characters immediately surrounding a found location must not be alphanumeric

Returns: character index (1-based) of first character of a found location, or 0,
if the text was not found.

Description:
Performs a simple sequential search for a string in a larger string, starting at the specified
position and working towards the start of the string.

Error Conditions: none

Created: 27.02.99 by P. Below}

function FindTextBackwards(findWhat, inString: string; startAt: Integer;
  caseSensitive, words: Boolean): Integer;
var
  i, patternlen, findpos: Integer;
  lastchar, firstchar: Char;
begin
  Result := 0; {assume failure}
  patternlen := Length(findWhat);
  {Do a few sanity checks on the parameters}
  if (patternlen = 0) or (startAt < patternlen) or (Length(inString) < patternlen)
    then
    Exit;
  if not caseSensitive then
  begin
    {convert both strings to lower case}
    findWhat := AnsiLowercase(findWhat);
    inString := AnsiLowercase(inString);
  end;
  i := startAt;
  lastchar := findWhat[patternlen];
  firstchar := findWhat[1];
  while (Result = 0) and (i >= patternlen) do
  begin
    if inString[i] = lastchar then
    begin
      findPos := i - patternlen + 1;
      if inString[findPos] = firstchar then
      begin
        {We have a candidate. Compare the substring of length patternlen
                                starting at findPos with findWhat.
                                With AnsiStrLComp we can do that without having to copy the substring to
        a temp string first.}
        if AnsiStrLComp(@findWhat[1], @inString[findPos], patternlen) = 0 then
        begin
          {We have a match!}
          Result := findPos;
          if words then
          begin
            {Check the characters surrounding the hit.
                                                For the hit to constitute a word they must not be alphanumeric.}
            if (findPos > 1) and IsCharAlphanumeric(inString[findPos - 1]) then
            begin
              {Not a match after all}
              Result := 0;
            end
            else
            begin
              if (i < Length(inString)) and IsCharAlphanumeric(inString[i + 1]) then
              begin
                {Not a match after all}
                Result := 0;
              end;
            end;
          end;
        end;
      end;
    end;
    Dec(i);
  end;
end;

Here's how to use it:

procedure TForm1.Button1Click(Sender: TObject);
var
  findPos: Integer;
begin
  findPos := FindTextBackwards(findEdit.Text, richedit1.Text, richedit1.selstart + 1,
    caseCheckbox.checked, wordsCheckbox.checked);
  if findPos > 0 then
  begin
    with richedit1 do
    begin
      selstart := findPos - 1;
      sellength := findEdit.GetTextLen;
      perform(em_scrollcaret, 0, 0);
      setfocus;
    end;
  end
  else
    showmessage('Text not found');
end;

2009. március 6., péntek

Easy way to compare dates


Problem/Question/Abstract:

Did you know that you can easily compare dates by using the "EncodeDate()"?

Answer:

Here are some examples:

uses
  SysUtils;

{...}

if (Date > EncodeDate(1997, 1, 1)) then
begin
  { display "this program has expired" }
end;

{...}

if (EncodeDate(1997, 1, 1) > EncodeDate(1996, 1, 1)) then
begin
  {...}
end;

2009. március 5., csütörtök

How to use MAPI to auto-send new mail


Problem/Question/Abstract:

How can I do ShellExecute(nil, 'open', 'mailto:abc@123.com', nil, nil, sw_shownormal) and auto-send new mail?

Answer:

You'd better try MapiSendMail. This uses the unit MAPI, if MAPI is configured correctly, this works quite fine.

uses
  Mapi;

{ ...}
var
  MapiMessage: TMapiMessage;
  MapiFileDesc: PMapiFileDesc;
  MError: Cardinal;
  FNStr: string;
  R, i: Integer;
begin
  FNStr := AttachedFileName;
  if R <> mrOK then
    exit;
  MapiFileDesc := New(PMapiFileDesc);
  try
    MapiFileDesc.lpszPathName := PChar(FNStr);
    MapiFileDesc.lpszFileName := '';
    with MapiMessage do
    begin
      ulReserved := 0;
      lpszSubject := nil;
      lpszNoteText := '';
      lpszMessageType := nil;
      lpszDateReceived := nil;
      lpszConversationID := nil;
      flFlags := 0;
      lpOriginator := nil;
      nRecipCount := 0;
      lpRecips := nil;
      nFileCount := 1;
      lpFiles := MapiFileDesc;
    end;
    MError := MapiSendMail(0, 0, MapiMessage, MAPI_DIALOG or MAPI_LOGON_UI or
      MAPI_NEW_SESSION, 0);
    if MError <> 0 then
      MessageDlg(SSendError, mtError, [mbOK], 0);
  finally
    Dispose(MapiFileDesc);
  end;
end;

2009. március 4., szerda

Scroll my control without flicker effect


Problem/Question/Abstract:

Scroll my control without flicker effect

Answer:

The easiest way to scroll the elements of a control is to force a complete repaint of the control. Unfortunately this produces the flicker effect. You may use

InvalidateRect(MyControl.Handle, nil, FALSE);

(important: last parameter = FALSE) to cause a complete redraw without erasing the background.

The best way to reduce this flickering is to use the ScrollWindow or ScrollWindowEx Windows API function. Look them up in your Win32.HLP file.

Another source of flickering can be from Windows using two messages to paint: WM_PAINT and WM_ERASEBKGND.

You may want to intercept all of the WM_ERASEBKGND messages and do all of your painting, including the background, in response to WM_PAINT messages in the Paint method:


type
  � TMyComponent = class(TWinControl)
    // ..
    � protected
      ��� procedure WMEraseBkgnd(var message: TWMEraseBkgnd);
    ����� message WM_ERASEBKGND;
    // ..
    �
  end;

  // ..

procedure TBMyComponent.WMEraseBkgnd(var message: TWMEraseBkgnd);
begin
  message.Result := 0
end;

2009. március 3., kedd

How to zoom a polygon


Problem/Question/Abstract:

How can I zoom a polygon? Using SetWorldTransform or how?

Answer:

Here's one possible way:

{ ... }
type
  TPolygon = array of TPoint;

procedure ZoomPolygon(var Polygon: TPolygon; const Center: TPoint; const Scale: Double);
var
  I: Integer;
begin
  for I := 0 to High(Polygon) do
  begin
    Polygon[I].X := Round(Scale * (Polygon[I].X - Center.X) + Center.X);
    Polygon[I].Y := Round(Scale * (Polygon[I].Y - Center.Y) + Center.Y);
  end;
end;

2009. március 2., hétfő

Splitting a string in an dynamic array


Problem/Question/Abstract:

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

Answer:

The following functions split a string in parts separated by a substring and return the parts in a dynamic string array:

interface

type
  TStringArray = array of string;

function Split(const str: string;
  const separator: string = ','): TStringArray;
function AnsiSplit(const str: string;
  const separator: string = ','): TStringArray;

implementation

uses sysutils;

function Split(const str: string;
  const separator: string): TStringArray;
// Returns an array with the parts of "str" separated by "separator"
var
  i, n: integer;
  p, q, s: PChar;
begin
  SetLength(Result, Occurs(str, separator) + 1);
  p := PChar(str);
  s := PChar(separator);
  n := Length(separator);
  i := 0;
  repeat
    q := StrPos(p, s);
    if q = nil then
      q := StrScan(p, #0);
    SetString(Result[i], p, q - p);
    p := q + n;
    inc(i);
  until q^ = #0;
end;

function AnsiSplit(const str: string;
  const separator: string): TStringArray;
// Returns an array with the parts of "str" separated by "separator"
// ANSI version
var
  i, n: integer;
  p, q, s: PChar;
begin
  SetLength(Result, AnsiOccurs(str, separator) + 1);
  p := PChar(str);
  s := PChar(separator);
  n := Length(separator);
  i := 0;
  repeat
    q := AnsiStrPos(p, s);
    if q = nil then
      q := AnsiStrScan(p, #0);
    SetString(Result[i], p, q - p);
    p := q + n;
    inc(i);
  until q^ = #0;
end;

Example:

procedure TForm1.Button1Click(Sender: TObject);
var
  a: TStringArray;
  i: integer;
begin
  a := Split('part1,part2,part3');
  for i := 0 to Length(a) - 1 do
  begin // Will show three dialogs
    ShowMessage(a[i]); // 'part1', 'part2', 'part3'
  end;
end;

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


Copyright (c) 2001 Ernesto De Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php

2009. március 1., vasárnap

How to intercept the maximize command


Problem/Question/Abstract:

How to intercept the maximize command

Answer:

If you want to restrict your window's maximum size (or minimum size, for that matter), you may try to intercept WM_SYSCOMMAND and check for the value of wParam.

More elegant is to intercept WM_GETMINMAXINFO, as the following example shows:


type
  TMyForm = class(TForm)
    procedure _WM_GETMINMAXINFO(var mmInfo: TWMGETMINMAXINFO); message
      wm_GetMinMaxInfo;
  end;

  //..

procedure TMyForm._WM_GETMINMAXINFO(var mmInfo: TWMGETMINMAXINFO);
begin
  with mmInfo.minmaxinfo^ do
  begin
    // allow at most half of the screen, and position it in the middle
    ptmaxposition.x := Screen.Width div 4;
    ptmaxposition.y := Screen.Height div 4;

    ptmaxsize.x := Screen.Width div 2;
    ptmaxsize.y := Screen.Height div 2;
  end;
end;

end.