2004. május 19., szerda

Delphi controls MS Office applications


Problem/Question/Abstract:

Delphi controls MS Office applications

Answer:

How can you remote control MS Office applications from your Delphi application? The Answer is to use a TOLEContainer.

It requires some interface knowledge to use the right object(s) and their properties. Some samples are added to Delphi demos, but all of them are targeted at MSWord. I have posted examples for Internet Explorer elsewhere and here is a sample for MSExcel:


// procedure is activated when OleOject activates user interface
// procedure copies TStringGrid content to an (OleObject) Excel sheet

procedure TForm1.OleContainer1Activate(Sender: TObject);
var
  ExcelSheet: Variant;
  Count,
    Curent: Variant;
  i,
    j: Integer;
begin
  // first we read how many sheets are open in a specified Excel document
  Count := OleContainer1.OleObject.Application.Sheets.Count;

  // then we read the number of a sheet to witch user wants to add StringGrid content
  Curent := StrToInt(OKBottomDlg.Edit2.Text);

  if Curent <> 0 then
  begin
    if Curent <= Count then
      // if the sheet with index Curent exist then copy content
    begin
      // first we activate the desiered sheet object
      OleContainer1.OleObject.Application.Sheets[Count].Activate;
      // pass the object to a variant variable
      ExcelSheet := OleContainer1.OleObject.Application.ActiveSheet;

      // now we can do what ever we like with it
      ExcelSheet.name := OKBottomDlg.Edit3.Text + IntToStr(Count);
      for i := 0 to StringGrid1.RowCount do
      begin
        for j := 0 to StringGrid1.ColCount do
        begin
          ExcelSheet.Cells(i, j) := StringGrid1.Cells[j, i]
        end
      end;
      // here we copy the content
    end
    else // else if the sheet we are trying to access doesn't exsist
    begin
      // we add new sheets untill the requested
      // user's index is reached ( curent variable )
      for i := Count + 1 to Curent do
      begin
        OleContainer1.OleObject.Application.Sheets.Add
      end;
      // again we do as above
      OleContainer1.OleObject.Application.Sheets[Curent].Activate;
      ExcelSheet := OleContainer1.OleObject.Application.ActiveSheet;
      ExcelSheet.name := OKBottomDlg.Edit3.Text + IntToStr(Count);
      for i := 0 to StringGrid1.RowCount do
      begin
        for j := 0 to StringGrid1.ColCount do
        begin
          ExcelSheet.Cells(i, j) := StringGrid1.Cells[j, i]
        end
      end;
    end
  end;
end;

2004. május 18., kedd

How to make the TJPEGImage component recognize the *.jpeg file extension


Problem/Question/Abstract:

How to make the TJPEGImage component recognize the *.jpeg file extension

Answer:

{ ... }
var
  MyImage: TImage;
begin
  JPEG := TJPEGImage.Create;
  try
    JPEG.LoadFromFile('C:\TEMP\SOMEIMAGE.JPEG');
    MainImage.Picture.Assign(JPEG);
    MainImage.Invalidate;
  finally
    JPEG.Free;
  end;

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

Retrieve a file's "Last Accessed" attribute


Problem/Question/Abstract:

Retrieve a file's "Last Accessed" attribute

Answer:

In Windows 95, you can see when a file was last accessed by right-clicking the file and selecting properties. You can retrieve this date easily with the following ready-to-use function:

function LastAccess(const filename: string): string;
var
  FileHandle: THandle;
  LocalFileTime: TFileTime;
  DosFileTime: DWORD;
  LastAccessedTime: TDateTime;
  FindData: TWin32FindData;
begin
  Result := ''; { never :-) }
  FileHandle := FindFirstFile(filename, FindData);
  if FileHandle <> INVALID_HANDLE_VALUE then
  begin
    Windows.FindClose(Handle);
    if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
    begin
      FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
      FileTimeToDosDateTime(LocalFileTime,
        LongRec(DosFileTime).Hi, LongRec(DosFileTime).Lo);
      LastAccessedTime := FileDateToDateTime(DosFileTime);
      Result := DateTimeToStr(LastAccessedTime);
    end;
  end;
end;

2004. május 16., vasárnap

Set the resolution of your screen


Problem/Question/Abstract:

This article shows how to set the resolution of your screen I pasted my whole unit below.

Answer:

unit Unit4;

interface

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

type
  TForm4 = class(TForm)
    ComboBox1: TComboBox;
    BitBtn1: TBitBtn;
    Bevel1: TBevel;
    procedure ComboBox1Change(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure Label4Click(Sender: TObject);
    procedure Button1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure Button1MouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure BitBtn1Click(Sender: TObject);
    procedure BitBtn1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure BitBtn1MouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form4: TForm4;
  Modes: array[0..255] of TDevMode;

implementation

uses cliprex2;

{$R *.DFM}

procedure TForm4.ComboBox1Change(Sender: TObject);
begin
  bitbtn1.Enabled := combobox1.ItemIndex >= 0;
  bitbtn1.enabled := true;
end;

procedure TForm4.FormCreate(Sender: TObject);
var
  DC: THandle;
  Bits: Integer;
  HRes: Integer;
  VRes: Integer;
  DM: TDevMode;
  ModeNum: LongInt;
  Ok: Bool;
  I: Byte;
begin

  DC := Canvas.Handle;
  Bits := GetDeviceCaps(DC, BITSPIXEL);
  HRes := GetDeviceCaps(DC, HORZRES);
  VRes := GetDeviceCaps(DC, VERTRES);

  ModeNum := 0;
  EnumDisplaySettings(nil, ModeNum, DM);
  Modes[ModeNum] := DM;
  Ok := True;
  while Ok do
  begin
    Inc(ModeNum);
    Ok := EnumDisplaySettings(nil, ModeNum, DM);
    Modes[ModeNum] := DM;
  end;

  for I := 0 to ModeNum - 1 do
  begin
    ComboBox1.Items.Add(Format('%d x %d, %d bits',
      [TDevMode(Modes[I]).dmPelsWidth,
      TDevMode(Modes[I]).dmPelsHeight,
        TDevMode(Modes[I]).dmBitsPerPel]));
    ComboBox1.ItemIndex := 0;
  end;
end;

procedure TForm4.FormActivate(Sender: TObject);

var
  DC: THandle;
  Bits: Integer;
  HRes: Integer;
  VRes: Integer;

begin

  DC := Canvas.Handle;
  Bits := GetDeviceCaps(DC, BITSPIXEL);
  HRes := GetDeviceCaps(DC, HORZRES);
  VRes := GetDeviceCaps(DC, VERTRES);

  combobox1.text := Format('%d x %d, %d bits', [HRes, VRes, Bits]);
  bitbtn1.enabled := false;
end;

procedure TForm4.Label4Click(Sender: TObject);
begin
  form4.hide;
end;

procedure TForm4.Button1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  bitbtn1.Font.Color := clblue;
end;

procedure TForm4.Button1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  bitbtn1.Font.Color := clblack;
end;

procedure TForm4.BitBtn1Click(Sender: TObject);
var
  NewMode: TDevMode;
  ChResult: LongInt;

begin
  NewMode := TDevMode(Modes[ComboBox1.ItemIndex]);
  NewMode.dmDisplayFrequency := 0;
  NewMode.dmDisplayFlags :=
    DM_BITSPERPEL and
    DM_PELSWIDTH and
    DM_PELSHEIGHT and
    DM_DISPLAYFLAGS;
  ChResult := ChangeDisplaySettings(NewMode, CDS_UPDATEREGISTRY);

  form4.hide;
end;

procedure TForm4.BitBtn1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  bitbtn1.font.color := clblue;
end;

procedure TForm4.BitBtn1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  bitbtn1.font.color := clblack;
end;

end.

2004. május 15., szombat

How to extract icons from a program or DLL


Problem/Question/Abstract:

How can I extract an icon from another executable or DLL through code?

Answer:

Use the Windows API function ExtractIcon(), passing it the instance handle of your application, the path name of the application you wish to extract the icon from, and the number of the icon you wish to extract:

var
  TheIcon: TIcon;
begin
  TheIcon := TIcon.Create;
  TheIcon.Handle := ExtractIcon(hInstance, 'C:\PATH\SOMEPROG.EXE', 0);
  {Do something with the icon}
  TheIcon.Free;
end;

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;