2009. március 28., szombat

How to communicate with a com port through RS232


Problem/Question/Abstract:

I want to develop a device that communicates through RS232 with the Com1 port. I know the port is connected to IRQ4 and I know the IO address of the 8250 status and data registers. I know how to do this mission in DOS (interrupt vector), but what I do not know is how to do something like this with Window 98 system and Delphi as a programming platform.

Answer:

The DOS solution is not recommended and will not work under NT anyway. The following unit has a class for the RS232 communication:


unit ComPort;

interface

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

type
  TComPort = class(TObject)
  private
    ComID, ComError: Integer;
    DcbOld: TDCB;
    CommTimeoutsOld: TCommTimeouts;
  protected
  public
    function Open(PortNo: integer): boolean;
    procedure Close;
    function Config(Baudrate: DWORD; ByteSize, StopBits, Parity: Byte): boolean;
    function ReadBlock(var Ch: array of char; BlockSize: dword): integer;
    function ReadChar(var Ch: char): boolean;
    function WriteBlock(var Ch: array of char; BlockSize: dword): boolean;
    function WriteChar(Ch: char): boolean;
    procedure Purge;
    function Error: integer;
    constructor Create;
  published
  end;

const
  cpReadError = 1;
  cpWriteError = 2;
  cpOpenError = 3;

implementation

constructor TComPort.Create;
begin
  inherited Create;
  ComID := -1;
end;

function TComPort.Open(PortNo: integer): boolean;
var
  CommTimeouts: TCommTimeouts;
  Port: string;
begin
  Port := 'COM' + IntToStr(PortNo);
  ComID := CreateFile(pChar(Port), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, 0, 0);
  if ComID <> -1 then
  begin
    GetCommState(ComID, DcbOld);
    GetCommTimeouts(ComID, CommTimeoutsOld);
    CommTimeouts.ReadIntervalTimeout := 1;
    CommTimeouts.ReadTotalTimeoutMultiplier := 1;
    CommTimeouts.ReadTotalTimeoutConstant := 1;
    CommTimeouts.WriteTotalTimeoutMultiplier := 10;
    CommTimeouts.WriteTotalTimeoutConstant := 10;
    SetCommTimeouts(ComID, CommTimeouts);
    ComError := 0;
  end
  else
    ComError := cpOpenError;
  Result := (ComID <> -1)
end;

procedure TComPort.Close;
begin
  if ComID <> -1 then
  begin
    SetCommState(ComID, DcbOld);
    SetCommTimeouts(ComID, CommTimeoutsOld);
    CloseHandle(ComID);
  end;
  ComID := -1;
end;

function TComPort.Config(Baudrate: DWORD; ByteSize, StopBits, Parity: Byte): boolean;
var
  Dcb: TDCB;
begin
  if ComID <> -1 then
  begin
    GetCommState(ComID, Dcb);
    Dcb.Baudrate := Baudrate;
    Dcb.ByteSize := ByteSize;
    Dcb.StopBits := StopBits;
    Dcb.Parity := Parity;
    SetCommState(ComID, Dcb);
  end
  else
    ComError := cpOpenError;
  Result := (ComID <> -1)
end;

function TComPort.ReadBlock(var Ch: array of char; BlockSize: dword): integer;
var
  rdBlockSize: dword;
begin
  Result := 0;
  if ComID <> -1 then
  begin
    rdBlockSize := BlockSize;
    if not ReadFile(ComID, Ch, BlockSize, rdBlockSize, nil) then
    begin
      GetLastError;
      ComError := cpReadError;
    end
    else
      Result := rdBlockSize;
  end
  else
    ComError := cpOpenError;
end;

function TComPort.ReadChar(var Ch: char): boolean;
var
  BlockSize: dword;
begin
  Result := False;
  if ComID <> -1 then
  begin
    if not ReadFile(ComID, Ch, 1, BlockSize, nil) then
    begin
      GetLastError;
      ComError := cpReadError;
    end
    else
      Result := (BlockSize = 1);
  end
  else
    ComError := cpOpenError;
end;

function TComPort.WriteBlock(var Ch: array of char; BlockSize: dword): boolean;
var
  W: dword;
begin
  Result := False;
  if ComID <> -1 then
  begin
    if not WriteFile(ComID, Ch, BlockSize, W, nil) then
    begin
      GetLastError;
      ComError := cpWriteError;
    end
    else
      Result := (BlockSize = W)
  end
  else
    ComError := cpOpenError;
end;

function TComPort.WriteChar(Ch: char): boolean;
var
  W: dword;
begin
  Result := False;
  if ComID <> -1 then
  begin
    if not WriteFile(ComID, Ch, 1, W, nil) then
    begin
      GetLastError;
      ComError := cpWriteError;
    end
    else
      Result := (W = 1)
  end
  else
    ComError := cpOpenError;
end;

procedure TComPort.Purge;
begin
  if ComID <> -1 then
  begin
    PurgeComm(ComID, Purge_TXABORT);
    PurgeComm(ComID, Purge_RXABORT);
    PurgeComm(ComID, Purge_TXCLEAR);
    PurgeComm(ComID, Purge_RXCLEAR);
  end
  else
    ComError := cpOpenError;
end;

function TComPort.Error: integer;
begin
  Result := ComError;
  ComError := 0;
end;

end.


And this is how you use this class:


{ ... }
var
  ComPort: TComPort;

In the Form1.OnCreate event:


ComPort := TComPort.Create;
ComPort.Open(1); {for COM1}


So now you can use ComPort.Config (see in Win32 API SetCommState for the Config parameter)


ComPort.WriteBlock
ComPort.WriteChar
ComPort.ReadBlock
ComPort.ReadChar

etc.


In the Form1.OnClose event:


ComPort.Close;
ComPort.Free;

2009. március 27., péntek

Hiding/showing the Windows taskbar


Problem/Question/Abstract:

Hiding/showing the Windows taskbar

Answer:

Use these functions to hide or show the Windows taskbar programmatically from your Delphi application:


procedure hideTaskbar;
var
  wndHandle: THandle;
  wndClass: array[0..50] of Char;
begin
  StrPCopy(@wndClass[0], 'Shell_TrayWnd');
  wndHandle := FindWindow(@wndClass[0], nil);
  ShowWindow(wndHandle, SW_HIDE); // This hides the taskbar
end;

procedure showTaskbar;
var
  wndHandle: THandle;
  wndClass: array[0..50] of Char;
begin
  StrPCopy(@wndClass[0], 'Shell_TrayWnd');
  wndHandle := FindWindow(@wndClass[0], nil);
  ShowWindow(wndHandle, SW_RESTORE); // This restores the taskbar
end;

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

How can i reboot my windows


Problem/Question/Abstract:

How can i reboot my windows?

Answer:

To Reboot your computer you just have to insert the next code:

ExitWindowsEx(EWX_FORCE and EWX_REBOOT);

This line of code while cause a LogOff in Windows 2000 and Windows XP.

If you need to ShutDown the line of code is:

ExitWindowsEx(EWX_FORCE and EWX_SHUTDOWN);

For more informaction about this, just write ExitWindowsEx in your program and then press F1 and will appear the help related with this function.

2009. március 25., szerda

Convert a Delphi form (from file) to text and vice versa


Problem/Question/Abstract:

Convert your Delphi form from .dfm format to text and vice versa

Answer:

use this function to convert:

  Example (DFM->TXT): ConvertFormToText('unit1.dfm');
  Example (TXT->DFM): ConvertTextToForm('unit1.txt');

uses
  SysUtils;

function ConvertFormToText(SourceFileName: string): boolean;
var
  InputStream, OutputStream: TFileStream;
  DestFileName: string;
begin
  result := true;

  { change the file extension to .txt }
  DestFileName := ChangeFileExt(SourceFileName, '.txt');

  { Create a file stream for the specified file }
  InputStream := TFileStream.Create(SourceFileName, fmOpenRead);
  OutputStream := TFileStream.Create(DestFileName, fmCreate);

  { convert }
  try
    try
      ObjectResourceToText(InputStream, OutputStream);
    except
      on EStreamError do
        Result := False;
    end
  finally
    { free memory }
    InputStream.Free;
    OutputStream.Free;
  end;
end;

function ConvertTextToForm(SourceFileName: string): boolean;
var
  InputStream, OutputStream: TFileStream;
  DestFileName: string;
begin
  result := true;

  DestFileName := ChangeFileExt(SourceFileName, '.dfm');

  InputStream := TFileStream.Create(SourceFileName, fmOpenRead);
  OutputStream := TFileStream.Create(DestFileName, fmCreate);

  try
    try
      ObjectTextToResource(InputStream, OutputStream);
    except
      on EStreamError do
        result := false;
    end
  finally
    InputStream.Free;
    OutputStream.Free;
  end;
end;

2009. március 24., kedd

How to implement string pattern matching with wildcards


Problem/Question/Abstract:

How to implement string pattern matching with wildcards

Answer:

There are many times when you need to compare two strings, but want to use wild cards in the match - all last names that begin with 'St', etc.

This function takes two strings and compares them. The first string can be anything, but should not contain pattern characters (* or ?). The pattern string can have as many of these pattern characters as you want. For example: MatchStrings('David Stidolph','*St*') would return True.}

function MatchStrings(source, pattern: string): Boolean;
var
  pSource: array[0..255] of Char;
  pPattern: array[0..255] of Char;

  function MatchPattern(element, pattern: PChar): Boolean;

    function IsPatternWild(pattern: PChar): Boolean;
    var
      t: Integer;
    begin
      Result := StrScan(pattern, ' * ') <> nil;
      if not Result then
        Result := StrScan(pattern, ' ? ') <> nil;
    end;

  begin
    if 0 = StrComp(pattern, ' * ') then
      Result := True
    else if (element^ = Chr(0)) and (pattern^ <> Chr(0)) then
      Result := False
    else if element^ = Chr(0) then
      Result := True
    else
    begin
      case pattern^ of
        ' * ':
          if MatchPattern(element, @pattern[1]) then
            Result := True
          else
            Result := MatchPattern(@element[1], pattern);
        ' ? ':
          Result := MatchPattern(@element[1], @pattern[1]);
      else
        if element^ = pattern^ then
          Result := MatchPattern(@element[1], @pattern[1])
        else
          Result := False;
      end;
    end;
  end;

begin
  StrPCopy(pSource, source);
  StrPCopy(pPattern, pattern);
  Result := MatchPattern(pSource, pPattern);
end;

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

How to map a variant OLEObject to an interface


Problem/Question/Abstract:

There seems to be no way to map the variant OLEObject to an interface (in our case Word 2000) or even cast it so at design time.

Answer:

Yes there is. The OleContainer's OleObject property holds the document as an IDispatch, and you can just cast to the interface you want. For example:

{ ... }
Doc: _Document;
{ ... }

OleContainer1.CreateObjectFromFile(Path, False);
OleContainer1.DoVerb(ovShow);
Doc := IDispatch(OleContainer1.OleObject) as _Document;

2009. március 22., vasárnap

How to detect the regional settings of a system


Problem/Question/Abstract:

How to detect the regional settings of a system

Answer:

Here is some sample code to get the language's abbreviated name, e.g.: ENU.

{ ... }
var
  Buffer: PChar;
  Size: integer;
begin
  Size := GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SABBREVLANGNAME, nil, 0);
  GetMem(Buffer, Size);
  try
    GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SABBREVLANGNAME, Buffer, Size);
    Result := string(Buffer);
  finally
    FreeMem(Buffer);
  end;
end;

This code gets the current Currency Symbol from Windows' regional settings:

function GetCurrencySymbol: string;
var
  Res: Cardinal;
begin
  Res := GetLocaleInfo(GetUserDefaultLCID, LOCALE_SCURRENCY, nil, 0);
  SetLength(Result, Res);
  Res := GetLocaleInfo(GetUserDefaultLCID, LOCALE_SMONDECIMALSEP, PChar(Result), Res);
  if Res = 0 then
    RaiseLastOSError;
end;

2009. március 21., szombat

Paint a TBitmap in disabled state


Problem/Question/Abstract:

How can I make an image to appear enabled and disabled (i.e going from original to disabled-grey and back)? I know that TImage doesn't support this feature, so how would I implement this?

Answer:

Everyone from you saw that standard TSpeedButton allow to show a loaded glyph in "disabled" state when your original glyph will be converted into gray-scheme.

Sometimes to create similar bitmap is useful not only for TSpeedButton.

You can use the next my CreateDisabledBitmap procedure where such "disabled" bitmap (Destination parameter) will be created from your original bitmap (Source).

procedure CreateDisabledBitmap(Source, Destination: TBitmap);
const
  ROP_DSPDxax = $00E20746;
var
  DDB, MonoBmp: TBitmap;
  IWidth, IHeight: Integer;
  IRect: TRect;
begin
  IWidth := Source.Width;
  IHeight := Source.Height;
  Destination.Width := IWidth;
  Destination.Height := IHeight;
  IRect := Rect(0, 0, IWidth, IHeight);
  Destination.Canvas.Brush.Color := clBtnFace;
  Destination.Palette := CopyPalette(Source.Palette);
  MonoBmp := nil;
  DDB := nil;
  try
    MonoBmp := TBitmap.Create;
    DDB := TBitmap.Create;
    DDB.Assign(Source);
    DDB.HandleType := bmDDB;
    { Create a disabled version }
    with MonoBmp do
    begin
      Assign(Source);
      HandleType := bmDDB;
      Canvas.Brush.Color := clBlack;
      Width := IWidth;
      if Monochrome then
      begin
        Canvas.Font.Color := clWhite;
        Monochrome := False;
        Canvas.Brush.Color := clWhite;
      end;
      Monochrome := True;
    end;
    with Destination.Canvas do
    begin
      Brush.Color := clBtnFace;
      FillRect(IRect);
      Brush.Color := clBtnHighlight;
      SetTextColor(Handle, clBlack);
      SetBkColor(Handle, clWhite);
      BitBlt(Handle, 1, 1, IWidth, IHeight, MonoBmp.Canvas.Handle, 0, 0, ROP_DSPDxax);
      Brush.Color := clBtnShadow;
      SetTextColor(Handle, clBlack);
      SetBkColor(Handle, clWhite);
      BitBlt(Handle, 0, 0, IWidth, IHeight, MonoBmp.Canvas.Handle, 0, 0, ROP_DSPDxax);
    end;
  finally
    DDB.Free;
    MonoBmp.Free;
  end;
  Source.Dormant;
end;

Sample of use:

procedure TfrmMain.ButtonClick(Sender: TObject);
var
  Destination: TBitmap;
begin
  Destination := TBitmap.Create;
  try
    CreateDisabledBitmap(Image1.Picture.Bitmap, Destination);
    Image2.Picture.Bitmap.Assign(Destination);
  finally
    Destination.Free
  end
end;

where Image1 is TImage where you have an original bitmap and TImage2 will a container for created disabled bitmap.

2009. március 20., péntek

How to play system sounds


Problem/Question/Abstract:

Is there any way to play system default sounds (like MessageBeep(mb_IconError) or mb_IconQuestion or these)? I need a way to play all the default sounds set in the system control (e.g. "new mail", "start windows" etc.).

Answer:

If you want to play the sound associated with "Empty Recycle Bin" then call the following procedure. Using the Key Name -> PlayRegisteredSound("EmptyRecycleBin") and Window's takes care of the rest.


procedure PlayRegisteredSound(SoundKeyName: string);
begin
  { call win32 api procedure PlaySound() }
  PlaySound(PChar(SoundKeyName), 0, SND_APPLICATION or SND_NODEFAULT or
    SND_ASYNC or SND_NOWAIT);
end;


Follow the RegKey by examining the keys beneath HKEY_CURRENT_USER\AppEvents\Schemes. Here you'll find where the wav files are registered and changed by the Sounds applet in the Control Panel.

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

Copy a file with or without a progressbar


Problem/Question/Abstract:

How to COPY a file with or without a progressbar

Answer:

function FileCopy(const SourceFile, TargetFile: string): Boolean; overload;
function FileCopy(const SourceFile, TargetFile: string; PB: TProgressBar): Boolean;
  overload;

function FileCopy(const SourceFile, TargetFile: string): Boolean;
begin
  Result := FileCopy(SourceFile, TargetFile, nil);
end;

function FileCopy(const SourceFile, TargetFile: string; PB: TProgressBar):
  Boolean;
const
  BlockSize = 1024 * 16;
var
  FSource, FTarget: Integer;
  BRead, Bwrite: Word;
  Buffer: Pointer;
begin
  Result := False;

  FSource := FileOpen(SourceFile, fmOpenRead + fmShareDenyNone); { Open Source }

  if FSource >= 0 then
  try
    if Assigned(PB) then
    begin
      PB.Position := 0;
      pb.Min := 0;
      pb.Max := (FileSeek(FSource, 0, 2));
      if (pb.Max > 2048) then
        pb.Step := pb.Max div 2048
      else
        pb.Step := pb.Max;
      FileSeek(FSource, 0, 0);
    end;
    FTarget := FileCreate(TargetFile); { Open Target }
    try
      getmem(Buffer, BlockSize);
      try
        FileSeek(FSource, 0, soFromBeginning);
        repeat

          BRead := FileRead(FSource, Buffer^, BlockSize);

          if assigned(PB) then
            PB.StepIt;

          BWrite := FileWrite(FTarget, Buffer^, Bread);

          if assigned(PB) then
            PB.StepIt;

        until (Bread = 0) or (Bread <> BWrite);
        if Bread = Bwrite then
        begin
          Result := True;
          if assigned(PB) then
            PB.Position := PB.Max;
        end;
      finally
        freemem(Buffer, BlockSize);
      end;
      FileSetDate(FTarget, FileGetDate(FSource));
    finally
      FileClose(FTarget);
    end;
  finally
    FileClose(FSource);
  end;
end;

2009. március 18., szerda

How to reach a graphic field without using a TDBImage


Problem/Question/Abstract:

How to reach a graphic field without using a TDBImage

Answer:

var
  Pic: TPicture;
begin
  Pic := TPicture.Create;
  dm.tbDeviceTypes.first;
  while not dm.tbDeviceTypes.EOF do
  begin
    Pic.Assign(dm.tbDeviceTypesFreePic);
    ImageList1.AddMasked(Pic.BitMap, ClWhite);
    dm.tbDeviceTypes.next;
  end;
end;

2009. március 17., kedd

How can I set the bar color of a TProgressbar?


Problem/Question/Abstract:

This code will show you, how you can set the bar color of a TProgressbar.

Answer:

procedure SetBarColor(Component: TProgressBar; Color: TColor);
begin
  SendMessage(Component.Handle, 1033, 0, Color);
end;

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

How to retrieve all available TBrushStyle values as a list of strings


Problem/Question/Abstract:

I need to get a list of strings (like a StringList) with the possible values for a TBrushStyle property (bsSolid, bsClear, bsHorizontal, for example). I want to build a ComboBox with this options. How can I set the property Items of my ComboBox directly with all the values from the enumerated type TBrushStyle? My ComboBox will be alike the Property Editor for this type.

Answer:

You can use runtime type information (RTTI) to do that. Below is an example:

uses
  {...}, TypInfo

procedure BrushStylesAsStrings(AList: TStrings);
var
  a: integer;
  pInfo: PTypeInfo;
  pEnum: PTypeData;
begin
  AList.Clear;
  pInfo := PTypeInfo(TypeInfo(TBrushStyle));
  pEnum := GetTypeData(pInfo);
  with pEnum^ do
  begin
    for a := MinValue to MaxValue do
      AList.Add(GetEnumName(pInfo, a));
  end;
end;

2009. március 15., vasárnap

Read the content of an Excel object embedded in a Word document


Problem/Question/Abstract:

I have an Excel object in a Word document. I want to read the content of the Excel object from my Delphi program. How can I do that?

Answer:

{ ... }
var
  AWordApplication: WordApplication;
  AWordDocument: WordDocument;
  AWorkBook: ExcelWorkBook;
  AWorkSheet: ExcelWorkSheet;
  AInlineShape: InlineShape;
  AFileName: OleVariant;
  TrueParam: OleVariant;
begin
  AWordApplication := CoWordApplication.Create;
  try
    FalseParam := False;
    AFileName := 'c:\wordexcel.doc';
    AWordDocument := AWordApplication.Documents.Open(AFileName, EmptyParam,
      EmptyParam,
      EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam,
      EmptyParam, EmptyParam, EmptyParam, EmptyParam);
    AInlineShape := AWordDocument.InlineShapes.Item(1);
    AInlineShape.Activate;
    AWorkBook := AWordDocument.InlineShapes.Item(1).OLEFormat.Object_ as
      ExcelWorkBook;
    AWorkSheet := AWorkBook.ActiveSheet as ExcelWorkSheet;
    ShowMessage(AWorkSheet.Cells.Item[2, 1].Text);
  finally
    AWordApplication.Quit(FalseParam, EmptyParam, EmptyParam);
    AWordApplication := nil;
    AWordDocument := nil;
  end;
end;