2004. február 14., szombat

Create a DBExpress-Connection at Runtime

Problem/Question/Abstract:

If you have a Webservice or a nonvisual component, you can't put a TSQLConnection on a form so you have to call the connection at runtime

Answer:

The normal way for Delphi and Kylix is just to check dbExpress, put a TSQLConnection on a form then double-click the TSQLConnection to display the Connection Editor and set parameter values (database path, connection name etc.) to indicate the settings.

But in our example, all goes by runtime (path and login) with dbExpress we don't need an alias or the BDE either.

procedure TVCLScanner.PostUser(const Email, FirstName, LastName: WideString);
var
Connection: TSQLConnection;
DataSet: TSQLDataSet;
begin
Connection := TSQLConnection.Create(nil);
with Connection do
begin
ConnectionName := 'VCLScanner';
DriverName := 'INTERBASE';
LibraryName := 'dbexpint.dll';
VendorLib := 'GDS32.DLL';
GetDriverFunc := 'getSQLDriverINTERBASE';
Params.Add('User_Name=SYSDBA');
Params.Add('Password=masterkey');
Params.Add('Database=milo2:D:\frank\webservices\umlbank.gdb');
LoginPrompt := False;
Open;
end;
DataSet := TSQLDataSet.Create(nil);
with DataSet do
begin
SQLConnection := Connection;
CommandText := Format('INSERT INTO kings VALUES("%s","%s","%s")',
[Email, FirstN, LastN]);
try
ExecSQL;
except
end;
end;
Connection.Close;
DataSet.Free;
Connection.Free;
end;


Sending commands to the server

Another possibilities is to send commands like CreateTable to the Server. For TSQLConnection, Execute takes three parameters: a string that specifies a single SQL statement that you want to execute, a TParams object that supplies any parameter values for that statement, and a pointer that can receive a TCustomSQLDataSet that is created to return records.

Note: Execute can only execute one SQL statement at a time. It is not possible to execute multiple SQL statements with a single call to Execute, as you can with SQL scripting utilities. To execute more than one statement, call Execute repeatedly.

It is relatively easy to execute a statement that does not include any parameters. For example, the following code in our example executes a CREATE TABLE statement (DataDefinitionLanguage) without any parameters on a TSQLConnection component:

procedure createUserTable;
var
Connection: TSQLConnection;
SQLstmt: string;
begin
Connection := TSQLConnection.Create(nil);
with Connection do
begin
ConnectionName := 'VCLScanner';
DriverName := 'INTERBASE';
LibraryName := 'dbexpint.dll';
VendorLib := 'GDS32.DLL';
GetDriverFunc := 'getSQLDriverINTERBASE';
Params.Add('User_Name=SYSDBA');
Params.Add('Password=masterkey');
with TWebModule1.create(nil) do
begin
getFile_DataBasePath;
Params.Add(dbPath);
free;
end;
LoginPrompt := False;
Connected := True;
SQLstmt := 'CREATE TABLE NewMaxCusts ' +
'( ' +
'  CustNo INTEGER NOT NULL, ' +
'  Company CHAR(40), ' +
'  State CHAR(2), ' +
'  PRIMARY KEY (CustNo) ' +
')';
try
Execute(SQLstmt, nil, nil);
except
raise
end;
Close;
Free;
end; //end Connection
end;


2004. február 13., péntek

Retrieve CPU information

Problem/Question/Abstract:

How to retrieve CPU information?

Answer:

Sometimes u need to know some information about the CPU like: brand id, factory speed, wich instruction set supported etc. If so, than u can use this code.

unit main;

interface

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

type
Tfrm_main = class(TForm)
img_info: TImage;
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure info(s1, s2: string);
end;

var
frm_main: Tfrm_main;
gn_speed_y: Integer;
gn_text_y: Integer;
const
gn_speed_x: Integer = 8;
gn_text_x: Integer = 15;
gl_start: Boolean = True;

implementation

{$R *.DFM}

procedure Tfrm_main.FormShow(Sender: TObject);
var
_eax, _ebx, _ecx, _edx: Longword;
i: Integer;
b: Byte;
b1: Word;
s, s1, s2, s3, s_all: string;
begin
//Set the startup colour of the image
img_info.Canvas.Brush.Color := clblue;
img_info.Canvas.FillRect(rect(0, 0, img_info.Width, img_info.Height));

gn_text_y := 5; //position of the 1st text

asm                //asm call to the CPUID inst.
mov eax,0         //sub. func call
db $0F,$A2         //db $0F,$A2 = CPUID instruction
mov _ebx,ebx
mov _ecx,ecx
mov _edx,edx
end;

for i := 0 to 3 do //extract vendor id
begin
b := lo(_ebx);
s := s + chr(b);
b := lo(_ecx);
s1 := s1 + chr(b);
b := lo(_edx);
s2 := s2 + chr(b);
_ebx := _ebx shr 8;
_ecx := _ecx shr 8;
_edx := _edx shr 8;
end;
info('CPU', '');
info('   - ' + 'Vendor ID: ', s + s2 + s1);

asm
mov eax,1
db $0F,$A2
mov _eax,eax
mov _ebx,ebx
mov _ecx,ecx
mov _edx,edx
end;
//06B1
//|0000| |0000 0000| |0000| |00| |00| |0110| |1011| |0001|
b := lo(_eax) and 15;
info('   - ' + 'Stepping ID: ', IntToStr(b));
b := lo(_eax) shr 4;
info('   - ' + 'Model Number: ', IntToHex(b, 1));
b := hi(_eax) and 15;
info('   - ' + 'Family Code: ', IntToStr(b));
b := hi(_eax) shr 4;
info('   - ' + 'Processor Type: ', IntToStr(b));
//31.   28. 27.   24. 23.   20. 19.   16.
//  0 0 0 0   0 0 0 0   0 0 0 0   0 0 0 0
b := lo((_eax shr 16)) and 15;
info('   - ' + 'Extended Model: ', IntToStr(b));

b := lo((_eax shr 20));
info('   - ' + 'Extended Family: ', IntToStr(b));

b := lo(_ebx);
info('   - ' + 'Brand ID: ', IntToStr(b));
b := hi(_ebx);
info('   - ' + 'Chunks: ', IntToStr(b));
b := lo(_ebx shr 16);
info('   - ' + 'Count: ', IntToStr(b));
b := hi(_ebx shr 16);
info('   - ' + 'APIC ID: ', IntToStr(b));

//Bit 18 =? 1     //is serial number enabled?
if (_edx and $40000) = $40000 then
info('   - ' + 'Serial Number ', 'Enabled')
else
info('   - ' + 'Serial Number ', 'Disabled');

s := IntToHex(_eax, 8);
asm                  //determine the serial number
mov eax,3
db $0F,$A2
mov _ecx,ecx
mov _edx,edx
end;
s1 := IntToHex(_edx, 8);
s2 := IntToHex(_ecx, 8);
Insert('-', s, 5);
Insert('-', s1, 5);
Insert('-', s2, 5);
info('   - ' + 'Serial Number: ', s + '-' + s1 + '-' + s2);

asm
mov eax,1
db $0F,$A2
mov _edx,edx
end;
info('', '');
//Bit 23 =? 1
if (_edx and $800000) = $800000 then
info('MMX ', 'Supported')
else
info('MMX ', 'Not Supported');

//Bit 24 =? 1
if (_edx and $01000000) = $01000000 then
info('FXSAVE & FXRSTOR Instructions ', 'Supported')
else
info('FXSAVE & FXRSTOR Instructions Not ', 'Supported');

//Bit 25 =? 1
if (_edx and $02000000) = $02000000 then
info('SSE ', 'Supported')
else
info('SSE ', 'Not Supported');

//Bit 26 =? 1
if (_edx and $04000000) = $04000000 then
info('SSE2 ', 'Supported')
else
info('SSE2 ', 'Not Supported');

info('', '');

asm     //execute the extended CPUID inst.
mov eax,$80000000   //sub. func call
db $0F,$A2
mov _eax,eax
end;

if _eax > $80000000 then //any other sub. funct avail. ?
begin
info('Extended CPUID: ', 'Supported');
info('   - Largest Function Supported: ', IntToStr(_eax - $80000000));
asm     //get brand ID
mov eax,$80000002
db $0F
db $A2
mov _eax,eax
mov _ebx,ebx
mov _ecx,ecx
mov _edx,edx
end;
s := '';
s1 := '';
s2 := '';
s3 := '';
for i := 0 to 3 do
begin
b := lo(_eax);
s3 := s3 + chr(b);
b := lo(_ebx);
s := s + chr(b);
b := lo(_ecx);
s1 := s1 + chr(b);
b := lo(_edx);
s2 := s2 + chr(b);
_eax := _eax shr 8;
_ebx := _ebx shr 8;
_ecx := _ecx shr 8;
_edx := _edx shr 8;
end;

s_all := s3 + s + s1 + s2;

asm
mov eax,$80000003
db $0F
db $A2
mov _eax,eax
mov _ebx,ebx
mov _ecx,ecx
mov _edx,edx
end;
s := '';
s1 := '';
s2 := '';
s3 := '';
for i := 0 to 3 do
begin
b := lo(_eax);
s3 := s3 + chr(b);
b := lo(_ebx);
s := s + chr(b);
b := lo(_ecx);
s1 := s1 + chr(b);
b := lo(_edx);
s2 := s2 + chr(b);
_eax := _eax shr 8;
_ebx := _ebx shr 8;
_ecx := _ecx shr 8;
_edx := _edx shr 8;
end;
s_all := s_all + s3 + s + s1 + s2;

asm
mov eax,$80000004
db $0F
db $A2
mov _eax,eax
mov _ebx,ebx
mov _ecx,ecx
mov _edx,edx
end;
s := '';
s1 := '';
s2 := '';
s3 := '';
for i := 0 to 3 do
begin
b := lo(_eax);
s3 := s3 + chr(b);
b := lo(_ebx);
s := s + chr(b);
b := lo(_ecx);
s1 := s1 + chr(b);
b := lo(_edx);
s2 := s2 + chr(b);
_eax := _eax shr 8;
_ebx := _ebx shr 8;
_ecx := _ecx shr 8;
_edx := _edx shr 8;
end;
info('Brand String: ', '');
if s2[Length(s2)] = #0 then
setlength(s2, Length(s2) - 1);
info('', '   - ' + s_all + s3 + s + s1 + s2);
end
else
info('   - Extended CPUID ', 'Not Supported.');
end;

procedure Tfrm_main.info(s1, s2: string);
begin
if s1 <> '' then
begin
img_info.Canvas.Brush.Color := clblue;
img_info.Canvas.Font.Color := clyellow;
img_info.Canvas.TextOut(gn_text_x, gn_text_y, s1);
end;
if s2 <> '' then
begin
img_info.Canvas.Brush.Color := clblue;
img_info.Canvas.Font.Color := clWhite;
img_info.Canvas.TextOut(gn_text_x + img_info.Canvas.TextWidth(s1), gn_text_y, s2);
end;
Inc(gn_text_y, 13);
end;

end.


2004. február 12., csütörtök

How to blend two pf24bit images using ScanLine


Problem/Question/Abstract:

Does anyone know how to implement basic alphablending without using Win2000 AlphaBlend function? I am trying to write a simple graphics program that will perform some alphablending on Win95 and Win98, but I don't know the necessary steps.

Answer:

Here's a method of blending two bitmaps. It uses 24-bit bitmaps and scanlines, so only works with D3 or higher. It assumes that variable b, a TBitmap, has pixelformat pf24bit.


type {for scanline access to 24-bit bitmaps}
  TRGBArray = array[0..32767] of TRGBTriple;
  pRGBArray = ^TRGBArray;

  {Gradient is one bitmap, b is the other. Amount is the percentage of the Gradient image to blend with b. tBufr is an existing TBitmap that's used internally for operations, b is the original bitmap.
  tBufr is sized to match b, and Gradient is stretched into it for this operation. All bitmaps are created and free'd elsewhere!}

procedure TForm1.MergeGradient(Amount: integer);
var
  pb, pc: pRGBArray;
  x, y: integer;
  GrdPct: Single;
  ImgPct: Single;
begin
  Screen.Cursor := crHourGlass;
  GrdPct := Amount / 100;
  ImgPct := 1 - GrdPct;
  tBufr.Width := b.Width;
  tBufr.Height := b.Height;
  tBufr.PixelFormat := pf24bit;
  tBufr.Canvas.StretchDraw(Rect(0, 0, tBufr.Width, tBufr.Height), Gradient);
  for x := 0 to tBufr.Height - 1 do
  begin
    pb := tBufr.ScanLine[x];
    pc := b.ScanLine[x];
    for y := 0 to tBufr.Width - 1 do
    begin
      pb[y].rgbtRed := Round(pb[y].rgbtRed * GrdPct + pc[y].rgbtRed * ImgPct);
      pb[y].rgbtBlue := Round(pb[y].rgbtBlue * GrdPct + pc[y].rgbtBlue * ImgPct);
      pb[y].rgbtGreen := Round(pb[y].rgbtGreen * GrdPct + pc[y].rgbtGreen * ImgPct);
    end;
  end;
  Image1.Picture.Assign(tBufr);
  Screen.Cursor := crDefault;
end;

2004. február 11., szerda

Ensure that every node in a TTreeView is unique


Problem/Question/Abstract:

I want to make sure that every node in my TreeView is unique - like making a new folder in Windows Explorer.

Answer:

It is a timing issue, it looks like you cannot set the node back to edit mode in the onEdited event. So post a user message to the form and set the node to edit mode in the handler for this message:

unit Unit1;

interface

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

const
  UM_EDITNODE = WM_USER;
type
  TUmEditNode = record
    msg: Cardinal;
    node: TTreenode;
    unused: Longint;
    result: Longint;
  end;

  TForm1 = class(TForm)
    Edit1: TEdit;
    Edit2: TEdit;
    TreeView1: TTreeView;
    procedure TreeView1Edited(Sender: TObject; Node: TTreeNode; var S: string);
  private
    { Private declarations }
    procedure UMEditNode(var msg: TUMeditNode); message UM_EDITNODE;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.TreeView1Edited(Sender: TObject; Node: TTreeNode; var S: string);
var
  n: TTreenode;
begin
  n := (Sender as TTreeview).Items[0];
  while n <> nil do
  begin
    if n <> Node then
    begin
      if AnsiCompareText(n.Text, S) = 0 then
      begin
        ShowMessage('Item already exists, use different text');
        S := node.text;
        PostMessage(handle, UM_EDITNODE, integer(node), 0);
        break;
      end;
    end;
    n := n.GetNext;
  end;
end;

procedure TForm1.UMEditNode(var msg: TUMeditNode);
begin
  if assigned(msg.node) then
    msg.node.edittext;
end;

end.

2004. február 10., kedd

Having a (send-to) Menu In Your Programs


Problem/Question/Abstract:

If you are interested in getting the windows send-to menu in your programs, try the following code !!

Answer:

Here Is The Whole Unit

unit uSendTo;

interface

uses
  SysUtils, Windows, Messages, Classes, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, Menus, ComCtrls, FileCtrl,
  ShellAPI, ShlObj, ActiveX, ComObj;

// Very basic example - a Form with a FileListBox and a PopupMenu...
type
  TForm1 = class(TForm)
    PopupMenu1: TPopupMenu;
    FileListBox1: TFileListBox;
    procedure FormCreate(Sender: TObject);
  private
    procedure SendToItemClick(Sender: TObject); // MenuItem event-handler
  public
    { Public declarations }
  end;

  // declare a special type of TMenuItem to store the EXE name...
type
  TMyMenuItem = class(TMenuItem)
  public Verb: string;
  end;

var
  Form1: TForm1;
implementation

{$R *.DFM}

// a pipe-delimited list of file extensions that are normally hidden...
const
  HiddenExtensions = '.LNK|.DESKLINK|.MYDOCS|.MAPIMAIL';

  // Get path to the SendTo folder (Like Madshi says) ...

function GetSendToFolder: string;
var
  pIDL: pItemIDList;
  Buffer: array[0..MAX_PATH] of char;
  Malloc: IMalloc;
begin
  SHGetSpecialFolderLocation(0, CSIDL_SENDTO, pIDL);
  ShGetPathFromIdList(pIDL, PChar(@Buffer));
  Result := Buffer;
  OLECheck(SHGetMalloc(Malloc));
  if pIDL <> nil then
    Malloc.Free(pIDL);
end;

// Recursive function to find all items in SendTo folder
// Creates sub-menu items if the folder has sub-directories...

procedure CreateMenuItems(Path: string; aMenuItem: TMenuItem);
var
  SR: TSearchRec;
  MI: TMyMenuItem;
  procedure AddIf;
  begin
    if SR.Attr and faDirectory <= 0 then
    begin // if it's a file
      MI := TMyMenuItem.Create(Form1);
      if pos(UpperCase(ExtractFileExt(SR.Name)), HiddenExtensions) > 0 then
        MI.Caption := ChangeFileExt(SR.Name, '')
      else
        MI.Caption := SR.Name;
      MI.Verb := Path + SR.Name;
      MI.OnClick := Form1.SendToItemClick; //Assign event handler
      aMenuItem.Add(MI)
    end
    else if SR.Name[1] <> '.' then
    begin // if it's a folder
      MI := TMyMenuItem.Create(Form1);
      MI.Caption := SR.Name;
      aMenuItem.Add(MI);
      CreateMenuItems(Path + SR.Name, MI); // Recursive call
    end;
  end;
begin
  if Path[Length(Path)] <> '\' then
    Path := Path + '\';
  if FindFirst(Path + '*', faAnyFile, SR) = 0 then
  begin
    AddIf;
    while FindNext(SR) = 0 do
      AddIf;
  end;
end;

// Find the EXE that the shortcut points to -
// Adapted from Elliott Shevin's TShortcutLink component
// (this could be modified to get the icon, ShowState, etc... )

function GetShortcutTarget(ShortcutFilename: string): string;
var
  Psl: IShellLink;
  Ppf: IPersistFile;
  WideName: array[0..MAX_PATH] of WideChar;
  pResult: array[0..MAX_PATH - 1] of Char;
  Data: TWin32FindData;
const
  IID_IPersistFile: TGUID = (D1: $0000010B; D2: $0000; D3: $0000; D4:
    ($C0, $00, $00, $00, $00, $00, $00, $46));
begin
  CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IID_IShellLinkA, psl);
  psl.QueryInterface(IID_IPersistFile, ppf);
  MultiByteToWideChar(CP_ACP, 0, pChar(ShortcutFilename), -1, WideName, Max_Path);
  ppf.Load(WideName, STGM_READ);
  psl.Resolve(0, SLR_ANY_MATCH);
  psl.GetPath(@pResult, MAX_PATH, Data, SLGP_UNCPRIORITY);
  Result := StrPas(@pResult);
end;

procedure TForm1.SendToItemClick(Sender: TObject);
begin
  // Just shows the filename - you could use ShellExecute or CreateProcess instead
  // But need some special handling for MyDocuments, Desktop and MailRecipient
  ShowMessage(GetShortcutTarget(TMyMenuItem(Sender).Verb));
end;

after compiling, it will be very easy to U to ge the needed functions and add them tto your own applications !!


!! OR TRY THIS MORE DEBUGGED VERSION !!!

Fixed:

1. Memory leak (no FindClose)
2. Kludge for removing file extensions that are normally hidden (now uses WinAPI to get the descriptive name)
3. Removed unessary duplication (Addif; while, etc - changed to repeat)
4. Added the all important but missing FormCreate event to show how this works...


// Recursive function to find all items in SendTo folder
// Creates sub-menu items if the folder has sub-directories...

procedure CreateMenuItems(Path: string; aMenuItem: TMenuItem);
var
  SR: TSearchRec;
  MI: TMyMenuItem;
  oSHFileInfo: SHFileInfo;

  procedure AddItemToMenu;
  begin
    MI := TMyMenuItem.Create(Form1);

    if SR.Attr and faDirectory <= 0 then
    begin // if it's a file
      // get system file information for item
      FillChar(oSHFileInfo, Sizeof(SHFileInfo), 0);

      // get systems' "proper" name for item
      SHGetFileInfo(PChar(Path + SR.Name), 0, oSHFileInfo, Sizeof(SHFileInfo),
        SHGFI_DISPLAYNAME);
      MI.Caption := oSHFileInfo.szDisplayName;

      MI.Verb := Path + SR.Name;
      MI.OnClick := Form1.SendToItemClick; //Assign event handler
      aMenuItem.Add(MI);

    end
    else if SR.Name[1] <> '.' then
    begin // if it's a folder
      MI.Caption := SR.Name;
      aMenuItem.Add(MI);
      CreateMenuItems(Path + SR.Name, MI); // Recursive call
    end;
  end;
begin
  Path := IncludeTrailingBackSlash(Path);
  if FindFirst(Path + '*', faAnyFile, SR) = 0 then
  begin
    try
      repeat
        AddItemToMenu;
      until (FindNext(SR) <> 0);
    finally
      FindClose(SR);
    end;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  CreateMenuItems(GetSendToFolder(), popupmenu1.Items);
  // to mimic the windows Send to menu you will:
  // 1. need to sort popupmenu1.Items alphabetically
  // 2. retrieve the icons
  // 3. find out how to execute them!
end;

Have Fun !!

2004. február 9., hétfő

Display a Property dialog for file, folder or drive


Problem/Question/Abstract:

How display the standard Property dialog for file, folder or drive?

Answer:

Sometimes you need show the standard dialog with file properties from own application (especially if you develop some file manager)

You may easy solve this task - just run next code:

function ShowFilePropertiesDialog(hWndOwner: HWND; const FileName: string): Boolean;
var
  Info: TShellExecuteInfo;
begin
  { Fill in the SHELLEXECUTEINFO structure }
  with Info do
  begin
    cbSize := SizeOf(Info);
    fMask := SEE_MASK_NOCLOSEPROCESS or
      SEE_MASK_INVOKEIDLIST or
      SEE_MASK_FLAG_NO_UI;
    wnd := hWndOwner;
    lpVerb := 'properties';
    lpFile := pChar(FileName);
    lpParameters := nil;
    lpDirectory := nil;
    nShow := 0;
    hInstApp := 0;
    lpIDList := nil;
  end;

  { Call Windows to display the properties dialog. }
  Result := ShellExecuteEx(@Info);
end;

This is the same dialog box that Windows Explorer displays when viewing an object's properties. For example, from this dialog user can change permissions for folder or check free space for drive.

You may specify a file name or folder name or drive letter. For example:

ShowFilePropertiesDialog(Application.Handle, 'd:\debit.xls')

or

ShowFilePropertiesDialog(Application.Handle, 'd:\Oracle')

or

ShowFilePropertiesDialog(Application.Handle, 'd:\')

2004. február 8., vasárnap

How can I add the current TWebbrowser site to the favorites?


Problem/Question/Abstract:

How can I add the current TWebbrowser site to the favorites?

Answer:

// You need: 1 TEdit, 2 TButtons, 1 TWebbrowser

const
  NotAllowed: set of Char = ['"'] + ['/'] + ['\'] + ['?'] + [':'] + ['*'] +
  ['<'] + ['>'] + ['|'];

implementation

{$R *.DFM}

function Load(Path, Key: string): string;
var
  Reg: TRegistry;
begin
  Reg := TRegistry.Create;
  try
    Reg.RootKey := HKEY_CURRENT_USER;
    Reg.OpenKey(Path, False);
    try
      Result := Reg.ReadString(Key);
    except
      Result := '';
    end;
    Reg.CloseKey;
  finally
    Reg.Free;
  end;
end;

function WinDir: string;
var
  WinDir: PChar;
begin
  WinDir := StrAlloc(MAX_PATH);
  GetWindowsDirectory(WinDir, MAX_PATH);
  Result := string(WinDir);
  if Result[Length(Result)] <> '\' then
    Result := Result + '\';
  StrDispose(WinDir);
end;

function GetSysDir: string;
var
  dir: array[0..MAX_PATH] of Char;
begin
  GetSystemDirectory(dir, MAX_PATH);
  Result := StrPas(dir);
end;

// Navigate to a page

procedure TForm1.Button1Click(Sender: TObject);
begin
  Webbrowser1.Navigate(edit1.Text);
end;

// Add the current page to the favorites

procedure TForm1.Button2Click(Sender: TObject);
var
  url: TStringList;
  fav: string;
  title, b: string;
  i: Integer;
  c: Char;
begin
  fav := Load('Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders',
    'Favorites');
  url := TStringList.Create;
  try
    url.Add('[InternetShortcut]');
    url.Add('URL=' + webbrowser1.LocationURL);
    url.Add('WorkingDirectory=' + WinDir());
    url.Add('IconIndex=0');
    url.Add('ShowCommand=7');
    url.Add('IconFile=' + GetSysDir() + '\url.dll');
    title := Webbrowser1.LocationName;
    b := '';
    for i := 1 to Length(title) do
    begin
      c := title[i];
      if not (c in NotAllowed) then
      begin
        b := b + Webbrowser1.LocationName[i];
      end;
    end;
    url.SaveToFile(fav + '\' + b + '.url');
  finally
    url.Free;
  end;
end;

end.

2004. február 7., szombat

Disable the functionality of sizing a form at runtime


Problem/Question/Abstract:

How to disable the functionality of sizing a form at runtime

Answer:

In some cases, developers would want to create a regular window (Form) in Delphi that contains some of the characteristics of a dialog box. For example, they do not want to allow their users to resize the form at runtime due to user interface design issues.

The following example demonstrates a way of handling the Windows message "WM_GetMinMaxInfo" which allows the developer to restrict the size of windows (forms) at runtime to a specific value. In this case, it will be used to disable the functionality of sizing the window (form) at runtime.

unit getminmax;

interface

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

type
  TForm1 = class(TForm)

  private
    { Private declarations }
    procedure WMGetMinMaxInfo(var Msg: TWMGetMinMaxInfo); message WM_GETMINMAXINFO;
    procedure WMInitMenuPopup(var Msg: TWMInitMenuPopup); message WM_INITMENUPOPUP;
    procedure WMNCHitTest(var Msg: TWMNCHitTest); message WM_NCHitTest;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.WMGetMinMaxInfo(var Msg: TWMGetMinMaxInfo);
begin
  inherited;
  with Msg.MinMaxInfo^ do
  begin
    ptMinTrackSize.x := form1.width;
    ptMaxTrackSize.x := form1.width;
    ptMinTrackSize.y := form1.height;
    ptMaxTrackSize.y := form1.height;
  end;
end;

procedure TForm1.WMInitMenuPopup(var Msg: TWMInitMenuPopup);
begin
  inherited;
  if Msg.SystemMenu then
    EnableMenuItem(Msg.MenuPopup, SC_SIZE, MF_BYCOMMAND or MF_GRAYED)
end;

procedure TForm1.WMNCHitTest(var Msg: TWMNCHitTest);
begin
  inherited;
  with Msg do
    if Result in [HTLEFT, HTRIGHT, HTBOTTOM, HTBOTTOMRIGHT,
      HTBOTTOMLEFT, HTTOP, HTTOPRIGHT, HTTOPLEFT] then
      Result := HTNOWHERE
end;
end.

A message handler for the windows message "WM_GetMinMaxInfo" in the code above was used to set the minimum and maximum TrackSize of the window to equal the width and height of the form at design time. That was actually enough to disable the resizing of the window (form), but the example went on to handle another couple of messages just to make the application look professional. The first message was the "WMInitMenuPopup" and that was to gray out the size option from the System Menu so that the application does not give the impression that this functionality is available. The second message was the "WMNCHitTest" and that was used to disable the change of the cursor icon whenever the mouse goes over one of the borders of the window (form) for the same reason which is not to give the impression that the resizing functionality is available.

2004. február 6., péntek

Check if a Point(x, y) is under the mouse cursor


Problem/Question/Abstract:

How to check if a Point(x, y) is under the mouse cursor

Answer:

You define a small rectangle around the mouse cursor and scan the points - in the MouseMove event:

{ ... }
var
  aRect: TRect;
begin
  aRect := rect(x - 5, y - 5, x + 5, y + 5);
  {Then scan your points:}
  for i := 0 to high(PointArray) do
    if PtInRect(aRect, PointArray[i]) then
    begin
      x := PointArray[i].x;
      y := PointArray[i].y;
      break;
    end;
end;

2004. február 5., csütörtök

How to determine whether a string contains binary data or normal readable text


Problem/Question/Abstract:

How to determine whether a string contains binary data or normal readable text

Answer:

Solve 1:

Well, actually there is not really a difference between binary and not. There is just a common "agreement" that everything below ASCII code 32 is a "binary" character.

function IsReadable(st: string): Boolean;
var
  i: Integer;
begin
  Result := false;
  for i := 1 to Length(st) do
    if st[i] < #32 then
      Exit;
  Result := true;
end;


Solve 2:

procedure GetVeryBasicFileType(const Path: string;
  var VeryBasicFileType: LongWord); overload;
var
  Fs: TFileStream;
  ExtCharCount, NothingCount, SpaceCount, LfCount, i, DidRead: Word;
  LastB,
    B: byte;
  ReadBuffer: array[0..MAX_FILE_DETECT_BUFFER] of byte;
begin
  VeryBasicFileType := VERY_BASIC_FILETYPE_UNKNOWN;
  if (FileExists(Path)) then
  begin
    Fs := TFileStream.Create(Path, fmOpenRead);
    try
      if (Fs.Size >= 1) then
      begin
        LfCount := 0;
        ExtCharCount := 0;
        SpaceCount := 0;
        NothingCount := 0;
        LastB := 0;
        Fs.Seek(0, soFromBeginning);
        DidRead := Fs.Read(ReadBuffer, SizeOf(ReadBuffer));
        for i := 0 to DidRead - 2 do
        begin
          B := ReadBuffer[i];
          if (B < 1) then
            Inc(NothingCount)
          else if (((B < 32) or (B > 127)) and not (B in [$0A, $0D, $21])) then
            Inc(ExtCharCount)
          else if ((B = $0A) or (B = $0D)) then
            Inc(LfCount)
          else if ((B = $21) and (LastB <> $21)) then
            Inc(SpaceCount);
          LastB := B;
        end;
        if (NothingCount > (DidRead div 30)) then
        begin
          if ((DidRead >= 4) and ((ReadBuffer[0] = $FF) and (ReadBuffer[1] = $FE)) or
            ((ReadBuffer[0] = $FE) and (ReadBuffer[1] = $FF))) then
          begin
            VeryBasicFileType := VERY_BASIC_FILETYPE_TEXT_UNICODE;
            Exit;
          end
          else
          begin
            VeryBasicFileType := VERY_BASIC_FILETYPE_BINARY;
            Exit;
          end;
        end;
        if (ExtCharCount > (DidRead div 3)) then
        begin
          if ((LfCount >= (DidRead div 60)) or (SpaceCount > (DidRead div 6))) then
            VeryBasicFileType := VERY_BASIC_FILETYPE_TEXT
          else
            VeryBasicFileType := VERY_BASIC_FILETYPE_BINARY;
        end
        else
        begin
          if ((ReadBuffer[0] = $EF) and (ReadBuffer[1] = $BB) and
                                                 (ReadBuffer[2] = $BF) and (LfCount > (DidRead div 60))) then
            VeryBasicFileType := VERY_BASIC_FILETYPE_TEXT_UTF8
          else
            VeryBasicFileType := VERY_BASIC_FILETYPE_TEXT;
        end;
      end
      else
        VeryBasicFileType := VERY_BASIC_FILETYPE_EMPTY;
    finally
      Fs.Free;
    end;
  end;
end;

2004. február 4., szerda

Generating random numbers


Problem/Question/Abstract:

How can I make Delphi 2 pick me any number within a range I specify (for example, between 0 and 100)? I'm guessing this is a fairly easy thing to do, but I couldn't find it in the manual...

Answer:

To get Delphi to pick any number within a specific range, you use the built-in random number generator. Here's a quick function to get you on your way:

function GetRandomInt(UpperRange: Integer): Integer;
begin
  Randomize;
  Result := Random(UpperRange);
end;

To get any number between 0 and 100, you'd call GetRandomInt, like so:

RandInteger := GetRandomInt(100);

So what's going on in the code? The first line, Randomize, initializes Delphi's random number generator. Then the second call, using the Random function, sets the function's result to a number between 0 and the UpperRange specified.

A quick note about the Random function: It's one of the very few functions in Delphi that can be overloaded; that is, you can have a variable number of parameters. With Random, it's either no parameters or an upper range. If you don't specify any parameters with Random (i.e. just declare Random;) the function will return a Real number between 0 and 1. If you specify an upper-range parameter, Random will return an integer between 0 and the upper range.

You might be thinking, "Wait a minute! I thought Delphi didn't support variable parameters other than open arrays."

It doesn't. But there are certain functions built into the Delphi engine that can take variable numbers of parameters. Random is one of them, and off the top of my head, I can't name others. In any case, play around with this. For another reference, look up Random in the help file.

2004. február 3., kedd

How to copy the registry files


Problem/Question/Abstract:

I want to copy the SYSTEM.DAT and USER.DAT files from the Windows directory. If I copy them using Explorer, manually, they copy fine. But, from Delphi 4 on Windows 95, using the CopyFile function, I get an access denied error.

Answer:

The registry files are always open, and it appears that the CopyFile API function doesn't use the appropriate sharing flags when it tries to copy them. This function should do the trick for you:


procedure CopyRegistryFile(const Source, Dest: string);
var
  SourceStream, DestStream: TFileStream;
begin
  SourceStream := TFileStream.Create(Source, fmOpenRead + fmShareDenyNone);
  try
    DestStream := TFileStream.Create(Dest, fmCreate);
    try
      DestStream.CopyFrom(SourceStream, SourceStream.Size);
    finally
      DestStream.Free
    end;
  finally
    SourceStream.Free
  end;
end;

2004. február 2., hétfő

Prevent a user from closes Windows


Problem/Question/Abstract:

When the user closes Windows having our application opened, it is possible that occur in a wrong moment (without recording data, in the middle of a process, etc).

Answer:

This can be avoided capturing the message that send Windows to all the applications when the user wants to close Windows: the  message WM_QUERYENSESSION

To capture the message and to send it to our treatment code of the message:

     TForm1 = class(TForm)
     ..........
       private
         procedure WMQueryEndSession(var Msg: TWMQueryEndSession); message WM_QUERYENDSESSION;
     ..........
     end;

Simply...we must add the next line in the Private part of the form:

    procedure WMQueryEndSession(var Msg: TWMQueryEndSession); message WM_QUERYENDSESSION;

and later, in the implementation, we put the treatment code of the message:

procedure TForm1.WMQueryEndSession(var Msg: TWMQueryEndSession);
begin
  MessageBox(Handle, 'Cierra antes el programa', nil, MB_OK);
  Msg.result := 0;
end;

If instead of aborting the close of Windows, we want that follows being accomplished, enough with which we change the Msg.result:=0 for Msg.result:=1.

NOTE: The behavior of the message defers in win98 and WinNT, as soon as watches you the help of the message WM_QUERYENDSESSION.

2004. február 1., vasárnap

CDO Emulation of VBasic value NOTHING


Problem/Question/Abstract:

I am currently writing a class that encapsulates the CDO (Collaboration Data Objects) in Delphi. For those of you who do not know what CDO is, it is a library that allows acces to MS-Exchange and Outlook folders,messages etc. much in the way of MAPI.

Answer:

One problem that kept cropping up from the examples in CDO.HLP was the use of something called "NOTHING" in the VB examples.

eg.

   Set objFolder = objSession.GetFolder(strFolderID)

    If objFolder Is Nothing Then
        Set objMessages = Nothing
        MsgBox "Unable to retrieve folder with specified ID"
        Exit Function
    End If

This is not "VARNULL",'VAREMPTY" or even "UNASSIGNED" in Delphi. Trying "if obFolder = VarNull" or any of above results in invalid typecast errors as do trying to compare to NIL.

What is it then ..... It is an IDispatch type which is set to NIL

The following 2 functions will emulate the behaviour of VB's NOTHING in Delphi.

// ===================================
// Emulate VB function IS NOTHING
// ===================================

function IsNothing(Obj: OleVariant): boolean;
begin
  Result := IDispatch(Obj) = nil;
end;

// ============================================
// Emulate VB function VarX := Nothing
// ============================================

function varNothing: IDispatch;
var
  Retvar: IDispatch;
begin
  Retvar := nil;
  Result := Retvar;
end;

--------------------------------------------------------------------------
Now the VBasic example can translate to ...

var
  objFolder, objMessages: OleVariant;

  objFolder := objSession.GetFolder(strFolderID);

if IsNothing(objFolder) then
begin
  objMessages := varNothing;
  ShowMessage('Unable to retrieve folder with specified ID');
  exit;
end;

For more information on CDO see CDO.HLP (From MS-Exchange CD) or Web Site
http://www.cdolive.com/exchange2000.htm