2004. május 14., péntek

Create a polygon-shaped form using regions


Problem/Question/Abstract:

How to create a polygon-shaped form using regions

Answer:

To start with, we need to make an array of points of all corners of the form (there can be as many as you want). Next we use the Windows API call CreatePolygonRgn to get a handle to the region we have just defined. Finally we need to set this region the window we want to be that shape using another API call SetWindowRgn. To see this in effect create a new project and in the forms onCreate event have:

procedure TForm1.FormCreate(Sender: TObject);
var
  Region: HRgn;
  Points: array[0..11] of TPoint;
begin
  {Define the points of a W shape}
  Points[0] := Point(0, 0);
  Points[1] := Point(50, 0);
  Points[2] := Point(180, 200);
  Points[3] := Point(218, 100);
  Points[4] := Point(256, 200);
  Points[5] := Point(385, 0);
  Points[6] := Point(435, 0);
  Points[7] := Point(256, 300);
  Points[8] := Point(218, 200);
  Points[9] := Point(180, 300);
  {Define the region}
  Region := CreatePolygonRgn(Points, 10, ALTERNATE);
  {Set the window to have the above defined region}
  SetWindowRgn(Handle, Region, True);
end;

2004. május 13., csütörtök

How to implement a 'Lasso'


Problem/Question/Abstract:

How to implement a 'Lasso'

Answer:

Here's a possible approach:

1. In the OnMouseDown event for the form that you are 'lasso-ing' controls on:


bMarquee := True;
{set a boolean so that you can differentiate between decisions that might have to be made during other mouse events}
ptOrigin := Point(X, Y); { get the starting point of the marquee }
ptMove := Point(X, Y); { initialize the stopping point }



Set the pen and brush attributes here or by calling a common procedure that can be reused elsewhere in the Unit.


Pen.Color := clBlack;
Pen.Width := 1;
Pen.Style := psDash;
Brush.Style := bsClear;


Then draw the marquee rectangle


DrawMarquee(ptOrigin, ptMove, pmNotXor);


2. In the OnMouseMove event for the form...


if bMarquee = True then
begin
  DrawMarquee(ptOrigin, ptMove, pmNotXor);
  DrawMarquee(ptOrigin, Point(X, Y), pmNotXor);
  ptMove := Point(X, Y);
  Canvas.Pen.Mode := pmCopy;
end;


3. In the OnMouseUp event for the form...


if bMarquee = True then
begin
  bMarquee := False;
  DrawMarquee(ptOrigin, Point(X, Y), pmNotXor);
  ptMove := Point(X, Y);
  {check for any intersections between the marquee frame and controls}
  { call the procedure that will highlight ( focus ) the desired controls}
end;


The DrawMarquee procedure...


procedure myForm.DrawMarquee(mStart, mStop: TPoint; AMode: TPenMode);
begin
  Canvas.Pen.Mode := AMode;
  Canvas.Rectangle(mStart.X, mStart.Y, mStop.X, mStop.Y);
end;

2004. május 12., szerda

Get File Created, Modified and Accessed dates


Problem/Question/Abstract:

How to get File Created, Modified and Accessed dates

Answer:

This function will return Created,Modified and Accessed datetimes of a given file. The datetimes are returned as TDateTime variables passed by REFERENCE. The function returns true if the file was found, else false. The dates are the same as displayed by EXPLORER when file properties is selected

// ================================================================
// Return the three dates (Created,Modified,Accessed
// of a given filename. Returns FALSE if file cannot
// be found or permissions denied. Results are returned
// in TdateTime OUT parameters
// ================================================================

function GetFileTimes(FileName: string;
  out Created: TDateTime;
  out Modified: TDateTime;
  out Accessed: TDateTime): boolean;
var
  FileHandle: integer;
  Cmd: boolean;
  FTimeC, FTimeA, FTimeM: TFileTime;
  LTime: TFileTime;
  STime: TSystemTime;
begin
  FileHandle := FileOpen(FileName, fmShareDenyNone);
  Created := 0.0;
  Modified := 0.0;
  Accessed := 0.0;

  if FileHandle < 0 then
    Cmd := false
  else
  begin
    Cmd := true;
    GetFileTime(FileHandle, @FTimeC, @FTimeA, @FTimeM);
    FileClose(FileHandle);

    // Created
    FileTimeToLocalFileTime(FTimeC, LTime);
    if FileTimeToSystemTime(LTime, STime) then
    begin
      Created := EncodeDate(STime.wYear, STime.wMonth, STime.wDay);
      Created := Created + EncodeTime(STime.wHour, STime.wMinute, STime.wSecond,
        STime.wMilliSeconds);
    end;

    // Accessed
    FileTimeToLocalFileTime(FTimeA, LTime);
    if FileTimeToSystemTime(LTime, STime) then
    begin
      Accessed := EncodeDate(STime.wYear, STime.wMonth, STime.wDay);
      Accessed := Accessed + EncodeTime(STime.wHour, STime.wMinute, STime.wSecond,
        STime.wMilliSeconds);
    end;

    // Modified
    FileTimeToLocalFileTime(FTimeM, LTime);
    if FileTimeToSystemTime(LTime, STime) then
    begin
      Modified := EncodeDate(STime.wYear, STime.wMonth, STime.wDay);
      Modified := Modified + EncodeTime(STime.wHour, STime.wMinute, STime.wSecond,
        STime.wMilliSeconds);
    end;

  end;

  Result := Cmd;
end;

2004. május 11., kedd

Filters for 256 color greyscale images


Problem/Question/Abstract:

Filters for 256 color greyscale images

Answer:

There are a lot of different filters that belong in different algorithm methods . A few things that are important to all methods:


Images must be 256 gray levels (I did not test them with color images)
We assume that image has the function RC (x, y) where x,y are the position of every pixel
0 < = X < = image_width - 1 and 0 < = Y < = Image_height - 1



Convolution filters

This is the most used method (also known as "moving window filters" and maybe you have already used it. For each pixel in range (1,1),(width-1,height-1) we calculate its new value using the following algorithm:



for j = 1 to height - 1
  for i = 1 to width - 1
  newcolor = a1 * RC(i, j - 1) + a2 * RC(i, j - 1) + a3 * RC(i + 1, j - 1) + b1 * RC(i - 1, j) + b2 * RC(i, j) +  b3 * RC(i + 1, j) + c1 * RC(i - 1, j + 1) + c2 * RC(i, j + 1) + c3 * RC(i + 1, j + 1);
newcolor = newcolor / kl;
newcolor = abs(newcolor);
if (newcolor > 255)newcolor = 255; {not greater than 255}
{do whatever you want here eg put new pixel color in a buffer}
end i
end j



Unfortunately in this method we have strange results in first & last row & column. That's why we start from row-column 1 (which is the second ) and we stop 1 row & column before end.

Here follow the names of the filters that belong into this method and the parameters a1..c3, kl that be used :



LOW_PASSn are noise removal filters. Images are getting smoother.
LAPLACE_ORIGINAL is Edge ehnancement filter.
LAPLACE is a special effect filter (looks like you type the image in abnormal paper)
LAPLACE_EDGE is Edge detection filter.
FOCUS is a sharpen filter (looks like you have changed the focus of the camera when
snapping the picture)


case LOW_PASS1: {
kl=9;
a1=1; a2=1; a3=1;
b1=1; b2=1; b3=1;
c1=1; c2=1; c3=1; break;
}
case LOW_PASS2: {
kl=10;
a1=1; a2=1; a3=1;
b1=1; b2=2; b3=1;
c1=1; c2=1; c3=1; break;
}
case LOW_PASS3: {
kl=16;
a1=1; a2=2; a3=1;
b1=2; b2=4; b3=2;
c1=1; c2=2; c3=1; break;
}
case LOW_PASS4: {
kl=5;
a1=0; a2=1; a3=0;
b1=1; b2=1; b3=1;
c1=0; c2=1; c3=0; break;
}
case LAPLACE_ORIGINAL: {
kl=1;
a1=-1; a2=-1; a3=-1;
b1=-1; b2=9; b3=-1;
c1=-1; c2=-1; c3=-1; break;
}
case LAPLACE: {
kl=1;
a1=1; a2=-2; a3=1;
b1=-2; b2=5; b3=-2;
c1=1; c2=-2; c3=1; break;
}
case LAPLACE_EDGE: {
kl=1;
a1=-1; a2=-1; a3=-1;
b1=-1; b2=8; b3=-1;
c1=-1; c2=-1; c3=-1; break;
}
case FOCUS: {
kl=1;
a1= 0; a2=-1; a3= 0;
b1=-1; b2= 5; b3=-1;
c1= 0; c2=-1; c3= 0; break;
}



Relief filter

Maxcolor is the maximum greyscale of the image. This is a very fancy filter. All new pixels have values near the (maxcolor/2) and for better results in viewing it is good to create a histogram equalization for the new image.



for j = 0 to height - 1
  for i = 0 to width - 1
  newcolor = RC(i, j) + ((maxcolor / 2) - RC(i - 2, j - 2));
newcolor = abs(newcolor); {hate negative values !!!}
if (newcolor > 255)newcolor = 255; {not greater than 255}
{do whatever you want here eg put new pixel color in a buffer}
end i
end j

2004. május 10., hétfő

Panel showing Enabled/Disabled in Children


Problem/Question/Abstract:

Often you disable all Controls within a Panel by simply setting the Enabled Property of the Panel. It works, however the user does not get any visual feedback.

Answer:

The following component code simply extends the Delphi Panel to properly show the Enabled State (True/False) within its children.

Extending the control is very simple. All  we need to do is to override and extend the default SetEnabled procedure. The new procedure will first call the original version and then rotate through all children and copy the state.

There is one drawback although, if there is a disabled control (XYZ) on the panel, you then disable the panel and enbale it again, the control (XYZ) will be enabled, too.

Anyway, often it is very useful. Here you go:

unit uRealPanel;

interface

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

type
  TRealPanel = class(TPanel)
  private
  protected
    procedure SetEnabled(Value: Boolean); override;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('gate(n)etwork', [TRealPanel]);
end;

{ TRealPanel }

procedure TRealPanel.SetEnabled(Value: Boolean);
var
  I: Integer;
begin
  inherited;
  if csDesigning in ComponentState then
    Exit;
  for I := 0 to Pred(ControlCount) do
    if Controls[I] is TWinControl then
      (Controls[I] as TWinControl).Enabled := Value;
end;

end.

2004. május 9., vasárnap

How to search for a pattern in a file


Problem/Question/Abstract:

I need to locate a pattern in a file (both text and binary) - just like the Pos function does with the strings. Preferably, it should deal with FileStream. Straightforward solution first seemed kind of expensive - that is to just plainly go through the stream comparing patterns on every step.

Answer:

Solve 1:

You can do it that way but it is much faster to load chunks of data into a sizeable buffer and do the search in the buffer. Here is an example:

function ScanFile(const filename: string; const forString: string; caseSensitive:
  Boolean): LongInt;
{ returns position of string in file or -1, if not found }
const
  BufferSize = $8001; { 32K + 1 bytes }
var
  pBuf, pEnd, pScan, pPos: Pchar;
  filesize: LongInt;
  bytesRemaining: LongInt;
  bytesToRead: Word;
  F: file;
  SearchFor: Pchar;
  oldMode: Word;
begin
  Result := -1; { assume failure }
  if (Length(forString) = 0) or (Length(filename) = 0) then
    Exit;
  SearchFor := nil;
  pBuf := nil;
  { open file as binary, 1 byte recordsize }
  AssignFile(F, filename);
  oldMode := FileMode;
  FileMode := 0; { read-only access }
  Reset(F, 1);
  FileMode := oldMode;
  try { allocate memory for buffer and pchar search string }
    SearchFor := StrAlloc(Length(forString) + 1);
    StrPCopy(SearchFor, forString);
    if not caseSensitive then { convert to upper case }
      AnsiUpper(SearchFor);
    GetMem(pBuf, BufferSize);
    filesize := System.Filesize(F);
    bytesRemaining := filesize;
    pPos := nil;
    while bytesRemaining > 0 do
    begin
      { calc how many bytes to read this round }
      if bytesRemaining >= BufferSize then
        bytesToRead := Pred(BufferSize)
      else
        bytesToRead := bytesRemaining;
      { read a buffer full and zero-terminate the buffer }
      BlockRead(F, pBuf^, bytesToRead, bytesToRead);
      pEnd := @pBuf[bytesToRead];
      pEnd^ := #0;
      { scan the buffer. Problem: buffer may contain #0 chars! So we
      treat it as a concatenation of zero-terminated strings. }
      pScan := pBuf;
      while pScan < pEnd do
      begin
        if not caseSensitive then { convert to upper case }
          AnsiUpper(pScan);
        pPos := StrPos(pScan, SearchFor); { search for substring }
        if pPos <> nil then
        begin { Found it! }
          Result := FileSize - bytesRemaining + LongInt(pPos) - LongInt(pBuf);
          Break;
        end;
        pScan := StrEnd(pScan);
        Inc(pScan);
      end;
      if pPos <> nil then
        Break;
      bytesRemaining := bytesRemaining - bytesToRead;
      if bytesRemaining > 0 then
      begin
        { no luck in this buffers load. We need to handle the case of the
                                search string spanning two chunks of file now. We simply go back a bit in
                                the file and read from there, thus inspecting some characters twice }
        Seek(F, FilePos(F) - Length(forString));
        bytesRemaining := bytesRemaining + Length(forString);
      end;
    end;
  finally
    CloseFile(F);
    if SearchFor <> nil then
      StrDispose(SearchFor);
    if pBuf <> nil then
      FreeMem(pBuf, BufferSize);
  end;
end;


Solve 2:

procedure TForm1.Button1Click(Sender: TObject);
var
  s: string;
  hFile: THandle;
  hFileMapObj: THandle;
  pSharedBuf: Pointer;
  Time0: Integer;
  p: PChar;
begin
  if not OpenDialog1.Execute then
    Exit;
  s := InputBox('Find', 'Match', '');
  Time0 := GetTickCount;
  hfile := 0;
  hFileMapObj := 0;
  pSharedBuf := nil;
  try
    hFile := FileOpen(OpenDialog1.FileName, fmOpenRead);
    Win32Check(hFileMapObj <> INVALID_HANDLE_VALUE);
    hFileMapObj := CreateFileMapping(hFile, nil, PAGE_READONLY, 0, 0, nil);
    Win32Check(hFileMapObj <> 0);
    pSharedBuf := MapViewOfFile(hFileMapObj, FILE_MAP_READ, 0, 0, 0);
    Win32Check(pSharedBuf <> nil);
    P := StrPos(PChar(pSharedBuf), PChar(s));
  finally
    if pSharedBuf <> nil then
      UnMapViewOfFile(pSharedBuf);
    if hFileMapObj <> 0 then
      CloseHandle(hFileMapObj);
    if hFile <> 0 then
      CloseHandle(hFile);
  end;
  if P = nil then
    Caption := Format('Not found, ticks=%d', [GetTickCount - Time0])
  else
    Caption := Format('Found it at pos %d, ticks=%d', [Integer(P - PChar(pSharedBuf)),
      GetTickCount - Time0]);
end;

2004. május 8., szombat

How to centre a MessageBox on a form


Problem/Question/Abstract:

How to centre a MessageBox on a form

Answer:

{ ... }
msgCaption: PChar; {var to hold caption}
{ ... }

procedure pmChangeMessageBox(var Msg: TMessage); message WM_USER + 1024;

procedure TForm1.pmChangeMessageBox(var Msg: TMessage);
var
  MBHwnd: THandle;
  MBRect: TRect;
  x, y, w, h: integer;
begin
  MBHwnd := FindWindow(MAKEINTRESOURCE(WC_DIALOG), msgCaption);
  if (MBHwnd <> 0) then
  begin
    GetWindowRect(MBHWnd, MBRect);
    w := MBRect.Right - MBRect.Left;
    h := MBRect.Bottom - MBRect.Top;
    {center horizontal}
    x := Form1.Left + ((Form1.Width - w) div 2);
    {keep on screen}
    if x < 0 then
      x := 0
    else if x + w > Screen.Width then
      x := Screen.Width - w;
    {center vertical}
    y := Form1.Top + ((Form1.Height - h) div 2);
    {keep on screen}
    if y < 0 then
      y := 0
    else if y + h > Screen.Height then
      y := Screen.Height - h;
    SetWindowPos(MBHWnd, 0, x, y, 0, 0, SWP_NOACTIVATE or SWP_NOSIZE or
      SWP_NOZORDER);
  end;
end;

Example use:

PostMessage(Handle, WM_USER + 1024, 0, 0);
msgCaption := 'Confirm';
MessageBox(Handle, 'Save changes?', msgCaption, MB_ICONQUESTION or MB_YESNOCANCEL);

2004. május 7., péntek

How to select all rows in a TDBGrid programmatically


Problem/Question/Abstract:

Can someone tell me how I can select all rows in a DBGrid in code by clicking a button?

Answer:

Something like this should work (untested):

procedure SelectAllinGrid(grid: TDBGrid);
var
  saveBK: TBookmark;
  i: integer;
begin
  with grid.DataSource.Dataset do
  begin
    for i := 0 to SelectedList.Count - 1 do
      FreeBookmark(SelectedList.Items[i]);
    SelectedList.Clear;
    saveBK := GetBookmark; { Save current record position }
    DisableControls;
    try
      First;
      while (not Eof) do
      begin
        SelectedList.Add(GetBookmark);
        Next;
      end;
    finally
      GotoBookmark(saveBK); { Restore original record position}
      Freebookmark(saveBK);
      EnableControls;
    end;
  end
end;

2004. május 6., csütörtök

Implement a Win32 look and feel "Browse for Folder" directory picker


Problem/Question/Abstract:

I'm looking for code that will let me implement a Win32 look and feel "Browse for Folder" directory picker. Like the one used in Project Options - > Directories/ Conditionals interface.

Answer:

procedure TMainForm.BrowseFolderActionExecute(Sender: TObject);
var
  pidl, pidlSelected: PItemIDList;
  bi: TBrowseInfo;
  szDirName: array[0..260] of AnsiChar;
begin
  {Get the root PIDL of the network neighborhood tree}
  if SHGetSpecialFolderLocation(Handle, CSIDL_DESKTOP, pidl) = NOERROR then
  begin
    {Populate a BROWSEINFO structure}
    bi.hwndOwner := Handle;
    bi.pidlRoot := pidl;
    bi.pszDisplayName := szDirName;
    bi.lpszTitle := 'Select directory';
    bi.ulFlags := BIF_RETURNONLYFSDIRS;
    bi.lpfn := nil;
    bi.lParam := 0;
    bi.iImage := -1;
    {Display the "Browse For Folder" dialog box}
    pidlSelected := SHBrowseForFolder(bi);
    {NULL indicates that Cancel was selected from the dialog box}
    if pidlSelected < > nil then
    begin
      SHGetPathFromIDList(pidlSelected, szDirName);
      ShowMessage(szDirName);
      {Release the PIDL of the computer name}
      CoTaskMemFree(pidlSelected);
    end;
    {Release the PIDL of the network neighborhood tree}
    CoTaskMemFree(pidl);
  end;
end;

2004. május 5., szerda

Code Insight


Problem/Question/Abstract:

Code Insight

Answer:

Here's a list of the new features in Delphi 3 which are collected under the name 'Code Insight':
Code Insight
Shortcut
Cancel Key
Extra
Code Completion
Ctrl Space
Esc
Can be sorted using right click in popup list.
Incremental search, up and down arrow, home and end keys for navigation.
Respects the visibility of the declared members of the class.
Code Parameters
Ctrl-Shift-Space
Esc

Argument Value List
Ctrl Space

Can be sorted using right click in popup list.
Must be specifically requested.
Displays constants, functions, and variables that are consistent with the argument required by the expression.
Code Templates
Ctrl J

if you type the short cut for the template and then Ctrl J you can skip the popup window.

The Code templates are stored in a ASCII file delphi32.dci which is stored in the Delphi\Bin Folder if you want to enter your templates in manually.

2004. május 4., kedd

How to load a DLL from a resource file and save it to disk


Problem/Question/Abstract:

Is it possible to copy a DLL into my own executable using the IDE only for exporting it after in my program? For example, I create an executable Test.exe and in the IDE I want to attach a resource that contains the DLL. And when my program is running I can export this resource to put a file on my hard disk. Is there a way to do that?

Answer:

Create a file called "mydllres.rc". Edit it and insert the line MYDLL RT_RCDATA "Mydll.dll". Then call the Borland compiler for resouces (you may need to adjust the paths) with BRCC32 mydllres.rc .

This will produce a output file called mydllres.res. Under the implementation header in the main unit add the following: {$R mydllres.res}. This will add the resource to the project.

The following procedure will save it to a file:

procedure savedll;
var
  myres: TResourceStream;
begin
  myres := TResourceStream.Create(hInstance, PChar('MYDLL'), RT_RCDATA);
  myres.SaveToFile(ExtractFilepath(Application.exename) + 'mydll.dll');
  myres.destroy;
end;

2004. május 3., hétfő

Add Interfaces to a List


Problem/Question/Abstract:

It's more efficient to control Interfaces in a List and ask with QueryInterface() which objects support an Interface

Answer:

First we need some Interfaces (the same goes also in Kylix, pure Interfaces are independent from COM, it's a feature of ObjectPascal):

type
  IKiss = interface(IUnknown)
    ['{19A231B1-269F-45A2-85F1-6D8A629CC53F}']
    procedure kiss; stdcall;
  end;

  ISpeak = interface(IUnknown)
    ['{B7F6F015-88A6-47AC-9176-87B6E313962D}']
    procedure sayHello; stdcall;
  end;

Second the interfaces must be implemented:

TDog = class(TInterfacedObject, ISpeak)
public
  procedure sayHello; stdcall;
end;

TFrench = class(TInterfacedObject, ISpeak, IKiss)
public
  procedure kiss; stdcall;
  procedure sayHello; stdcall;
end;

TEnglish = class(TInterfacedObject, ISpeak)
public
  procedure sayHello; stdcall;
end;

e.g. the dog with

procedure TDog.sayHello;
begin
  showmessage('dog is barking wauwau');
end;

Now we add the instances of the interface in the list, using the defined type TInterfaceList so we are able to ask with QueryInterface if an object supports an Interface, in our example if a dog as an object can kiss or just sayhello:

procedure TForm1.btnCollectClick(Sender: TObject);
var
  collection: TInterfaceList;
  i: Integer;
  aObjspeak: ISpeak;
  aObjKiss: IKiss;
begin
  collection := TinterfaceList.create;
  try
    with collection do
    begin
      add(TEnglish.create);
      add(TFrench.create);
      add(TDog.create);
    end;
    for i := 0 to collection.count - 1 do
    begin
      aObjSpeak := collection[i] as ISpeak; //TFrench, TEnglish, TDog
      if aObjSpeak <> nil then
        aObjSpeak.sayHello;
      collection[i].queryInterface(IKiss, aObjKiss); //only TFrench
      if aObjKiss <> nil then
        aObjKiss.kiss;
    end;
  finally
    collection.free;
  end;
end;

2004. május 2., vasárnap

RGB and HSV conversions


Problem/Question/Abstract:

Sometimes it is best to deal with colors as HSV rather than RGB. The artical explains a little bit what HSV is and includes source for converting between the two.

Answer:

HSV is Hue, Saturation, and Value.

HSV:

Hard to explain without a picture so you will have to use your imagination...

Hue:

Draw a circle in your head, the circle is 0 to 360 degrees (or 359 :-) ).  On the outer edge of the circle, place a red dot at 0 degrees, a green dot at 120 degrees and a blue dot at 240 degrees.  Those are the main points.  The other points between these 3 colors are interpolated... for example yellow is between red and green at 60 degrees (equal red + green = yellow), cyan is between green and blue at 180 degrees, magenta is between blue and red at 300 degrees.  Then between yellow and red is another and you keep breaking it down until your circle is full.  The outer edge from 0 to 360 degrees is the hue.

Saturation:

The center of the circle is white.  The color blends with the other colors to white as you go from the outside of the circle to the center.  The outer egde is saturation of 1 and the center is 0 (white).

Value:

Value is simply the intensity of the color.

You already know RGB I assume since you are a programmer.

I played around with my digital camera and took a picture of my brown computer chair.  I created an algorithm that turned my chair green.  It was easy with HSV, I simply used photoshop to see what the hue was of the chair.  Then I rotated the hue so that the chair was in the green range.  Boom, the chair was green.

Here they are:

http://www.eggcentric.com/eimages/greenchair.jpg
http://www.eggcentric.com/eimages/brownchair.jpg

Here is the source of procedures to convert between RGB and HSV and back again.  You can also download it from the link.

unit RGBHSV;
{
  William Egge, public@eggcentric.com
  http://www.eggcentric.com

  This unit converts between RGB and HSV color models.

  procedure HSVToRGB(const H, S, V: Single; out R, G, B: Single);
    in
    H = Hue.  Range is from 0..1.  0.5 = 180 degrees, 1 = 360. or H < 0 for gray
    S = Satration.  Range is 0..1 where 0 is white and 1 is no saturation.
    V = Value.  Range is 0..255

    out
    R = 0..255
    G = 0..255
    B = 0..255

    If H < 0 then the result is a gray value R=V, G=V, B=V

  procedure RGBToHSV(const R, G, B: Single; out H, S, V: Single);
    in
    R = 0..255
    G = 0..255
    B = 0..255

    out
    H = Hue. -1 for grey scale or range 0..1.  0..1 represents 0..360 degrees
    S = Saturation. Range = 0..1. 0 = white, 1 = no saturation.
    V = Value or intensity. Range 0..255
}

interface
uses
  Math;

procedure HSVToRGB(const H, S, V: Single; out R, G, B: Single);
procedure RGBToHSV(const R, G, B: Single; out H, S, V: Single);

implementation

procedure HSVToRGB(const H, S, V: Single; out R, G, B: Single);
const
  SectionSize = 60 / 360;
var
  Section: Single;
  SectionIndex: Integer;
  f: single;
  p, q, t: Single;
begin
  if H < 0 then
  begin
    R := V;
    G := R;
    B := R;
  end
  else
  begin
    Section := H / SectionSize;
    SectionIndex := Floor(Section);
    f := Section - SectionIndex;
    p := V * (1 - S);
    q := V * (1 - S * f);
    t := V * (1 - S * (1 - f));
    case SectionIndex of
      0:
        begin
          R := V;
          G := t;
          B := p;
        end;
      1:
        begin
          R := q;
          G := V;
          B := p;
        end;
      2:
        begin
          R := p;
          G := V;
          B := t;
        end;
      3:
        begin
          R := p;
          G := q;
          B := V;
        end;
      4:
        begin
          R := t;
          G := p;
          B := V;
        end;
    else
      R := V;
      G := p;
      B := q;
    end;
  end;
end;

procedure RGBToHSV(const R, G, B: Single; out H, S, V: Single);
var
  RGB: array[0..2] of Single;
  MinIndex, MaxIndex: Integer;
  Range: Single;
begin
  RGB[0] := R;
  RGB[1] := G;
  RGB[2] := B;

  MinIndex := 0;
  if G < R then
    MinIndex := 1;

  if B < RGB[MinIndex] then
    MinIndex := 2;

  MaxIndex := 0;
  if G > R then
    MaxIndex := 1;

  if B > RGB[MaxIndex] then
    MaxIndex := 2;

  Range := RGB[MaxIndex] - RGB[MinIndex];

  // Check for a gray level
  if Range = 0 then
  begin
    H := -1; // Can't determine on greys, so set to -1
    S := 0; // Gray is at the center;
    V := R; // could choose R, G, or B because they are all the same value.
  end
  else
  begin
    case MaxIndex of
      0: H := (G - B) / Range;
      1: H := 2 + (B - R) / Range;
      2: H := 4 + (R - G) / Range;
    end;
    S := Range / RGB[MaxIndex];
    V := RGB[MaxIndex];
    H := H * (1 / 6);
    if H < 0 then
      H := 1 + H;
  end;
end;

end.


Component Download: http://www.eggcentric.com/download/rgbhsv.zip

2004. május 1., szombat

Insert text at bookmark positions of a Word document


Problem/Question/Abstract:

How to insert text at bookmark positions of a Word document

Answer:

procedure WordBookInsert(v: OleVariant; sgoto, sdata: string);
begin
  try
    {make sure we have passed a word.application level variant}
    if not varisempty(v) then
    begin
      V.Selection.goto(What := wdGoToBookmark, Name := sgoto);
      V.Selection.TypeText(Text := SDATA);
    end;
  except
    {trap OLE errors and display message if it fails}
    on E: sysutils.exception do
    begin
      showmessage(e.message);
    end;
  end;
end;