2005. február 2., szerda
Link Label Component
Problem/Question/Abstract:
I have seen many tips on how to call the default browser and open a web page, yet no component in DKB that allows to simply be placed on a form at design time.
Answer:
This component was developed for the German-language forum Delphi-PRAXiS by myself. There is not much to say about it. Simply copy the source code into a new Delphi unit save it and install the component in Delphi.
Afterwards you may place it on your form, set link and caption, adjust the colors for Hot-Link, Visited and Unvisited. Just like a link within your HTML. You may place a link to an e-mail address also, by simply preceding the email address with a mailto:.
======================== CODE START ========================
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Unit Name : uDPLinkLabel
* Copyright : Copyright © 2001, 2002 by gate(n)etwork. All Rights Reserved.
* Author : Daniel Wischnewski
* Freeware : This source is released under the Mozilla Public License. It may
* be reproduced, as long as all references to its original source
* are maintained.
* The most recent version is publicly available at
* http://www.Delphi-PRAXiS.net
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
//: Enth�lt eine Internetlink-Label-Komponente f�r die Mitglieder der Delphi-PRAXiS.
unit uDPLinkLabel;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
//: Komponente zur Bereitstellung von Links innerhalb von Delphi-Anwendungen
TDPLinkLabel = class(TCustomLabel)
private
FHoverLinkFont: TFont;
FHyperLink: string;
FLinkFont: TFont;
FMouseHover: Boolean;
FVisited: Boolean;
FVisitedLinkFont: TFont;
procedure FontChanged(Sender: TObject);
procedure SetHoverLinkFont(Value: TFont);
procedure SetHyperLink(Value: string);
procedure SetLinkFont(Value: TFont);
procedure SetVisited(Value: Boolean);
procedure SetVisitedLinkFont(Value: TFont);
procedure UpdateLinkFont;
protected
procedure Click; override;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ExecuteHyperLink(aLink: string = '');
published
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BiDiMode;
property Caption;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FocusControl;
property HoverLinkFont: TFont read FHoverLinkFont write SetHoverLinkFont;
property HyperLink: string read FHyperLink write SetHyperLink;
property Layout;
property LinkFont: TFont read FLinkFont write SetLinkFont;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
property ParentBiDiMode;
property ParentColor;
property ParentShowHint;
property PopupMenu;
property ShowAccelChar;
property ShowHint;
property Transparent;
property Visible;
property Visited: Boolean read FVisited write SetVisited;
property VisitedLinkFont: TFont read FVisitedLinkFont write
SetVisitedLinkFont;
property WordWrap;
end;
procedure Register;
implementation
uses
ShellAPI;
procedure Register;
begin
RegisterComponents('Delphi-PRAXiS', [TDPLinkLabel]);
end;
{ TDPLinkLabel }
constructor TDPLinkLabel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// create default link font object
FLinkFont := TFont.Create;
FLinkFont.OnChange := FontChanged;
FLinkFont.Color := clBlue;
FLinkFont.Style := [fsUnderline];
// set inherited font
Font := LinkFont;
// create visit link font object
FVisitedLinkFont := TFont.Create;
FVisitedLinkFont.OnChange := FontChanged;
FVisitedLinkFont.Color := clPurple;
FVisitedLinkFont.Style := [fsUnderline];
// create hover link font object
FHoverLinkFont := TFont.Create;
FHoverLinkFont.OnChange := FontChanged;
FHoverLinkFont.Color := clRed;
FHoverLinkFont.Style := [fsUnderline];
// initialize vars
FMouseHover := False;
FVisited := False;
Caption := 'Delphi-PRAXiS';
FHyperLink := 'http://www.Delphi-PRAXiS.net';
// override initialization of previous vars
Cursor := crHandPoint;
end;
destructor TDPLinkLabel.Destroy;
begin
inherited Destroy;
// free link font objects
FLinkFont.Free;
FHoverLinkFont.Free;
FVisitedLinkFont.Free;
end;
procedure TDPLinkLabel.Click;
begin
// the onClick method will be overriden only, if a link is assigned to the
// Link property of the component and no custom on-click handler is assigned
if (not Assigned(OnClick)) and (Action = nil) and (ActionLink = nil) and (
HyperLink <> '') then
// call link
ExecuteHyperLink
else
// work standard control click routine
inherited;
end;
procedure TDPLinkLabel.CMMouseEnter(var Message: TMessage);
begin
inherited;
// mouse enters link - hover color effective
FMouseHover := True;
UpdateLinkFont;
end;
procedure TDPLinkLabel.CMMouseLeave(var Message: TMessage);
begin
inherited;
// mouse leaves link - hover color not effective anymore
FMouseHover := False;
UpdateLinkFont;
end;
procedure TDPLinkLabel.ExecuteHyperLink(aLink: string = '');
var
UseLink: string;
begin
// set link for execution
if Trim(aLink) = '' then
UseLink := Trim(HyperLink)
else
UseLink := Trim(aLink);
// check link data
if Trim(UseLink) = '' then
// raise exception on empty link
raise Exception.Create('No link for launching web browser.');
// load default browser with link
ShellExecute(0, nil, PChar(HyperLink), nil, nil, SW_SHOW);
// HyperLink was visited, no special link passed
if Trim(aLink) <> '' then
Visited := True;
end;
procedure TDPLinkLabel.FontChanged(Sender: TObject);
begin
// need to inform preceding class of possible changes in font
UpdateLinkFont;
end;
procedure TDPLinkLabel.SetHoverLinkFont(Value: TFont);
begin
FHoverLinkFont.Assign(Value);
UpdateLinkFont;
end;
procedure TDPLinkLabel.SetHyperLink(Value: string);
begin
if FHyperLink <> Value then
begin
FHyperLink := Value;
Visited := False;
if Caption = '' then
Caption := HyperLink;
end;
end;
procedure TDPLinkLabel.SetLinkFont(Value: TFont);
begin
FLinkFont.Assign(Value);
UpdateLinkFont;
end;
procedure TDPLinkLabel.SetVisited(Value: Boolean);
begin
if FVisited <> Value then
begin
FVisited := Value;
UpdateLinkFont;
end;
end;
procedure TDPLinkLabel.SetVisitedLinkFont(Value: TFont);
begin
FVisitedLinkFont.Assign(Value);
UpdateLinkFont;
end;
procedure TDPLinkLabel.UpdateLinkFont;
begin
// assign font property the appropriate font data
if FMouseHover then
Font := HoverLinkFont
else if Visited then
Font := VisitedLinkFont
else
Font := LinkFont;
end;
end.
========================= CODE END =========================
2005. február 1., kedd
Moveable/Sizable TPanel with standard or color SizeGrip
Problem/Question/Abstract:
How can I move/resize a TPanel at runtime. Also can I place a sizegrip on the panel and make it a different color then Grey?
Answer:
Many times an application may need to move or resize items on a form. The custom panel presented here provides the ability to move the panel by holding down the left mouse button and dragging the panel to a new location. The size can be adjusted by holding the left mouse button down in the lower right hand corner of the panel as done when resizing a form. There is a property to show/hide the SizeGrip and even change the style of the SizeGrip so that the color can be changed in the event the panel needs to be different then battleship grey. There is two unusual properties FreezeTopAt and FreezeTop which allow you to restrict how far the top can be moved on the parent form. It has been tested with D5 but not D6, see comments inside concerning D6.
unit SizeGripPanel;
{
Description:
This component, a decendent of TPanel provides methods to size and move
the panel by using the mouse. The only restriction for sizing the panel
is that is must be done using the SizeGrip located at the bottom right
part of the panel.
There are two additional events, OnMove and OnSize. Yes you guessed
correct, the are hooked into when a user moves or resizes the panel.
ColoredGrip when True allows the grip to be colored unlike the default
style grip.
Author:
Kevin S. Gallagher
gallaghe@teleport.com
Version
1.0.2
Copyrights:
This is a freeware component. Use at your own risk. You may not sell
or distruibute the component for profit.
Notes:
Originally created in D4, ported to D5.
I am not sure what all needs to change for D6 since I don't have it yet.
It will work as reported from one programmer by hacking some code i.e.
Changing the USES clause and removing the "About" code. There should be
away to make the "About" code work, will fix it once I get D6.
Limitations:
The Grip as is can not assume the color of the panel, for a quick
solution I added the property . For myself it doesn't matter
since I am always using drab grey. If anyone wants to change this, feel
free, just email me the changes.
IF YOU GET THIS TO WORK UNDER D6 SEND ME THE CHANGES PLEASE SO I CAN POST
THE CHANGES.
Revisions
KSG 02.08.01
Added the property "FreezeTop" which when set will not allow vertical
movement of the panel. "FreezeTopAt" control the topmost point the
panel can move too.
KSG 09.10.01
Found flaw in code to set Grip visible, fixed.
Attempted to make work under D6 w/o D6 available.
}
interface
{$IFDEF VER140}
uses
Windows, Messages, Classes, ExtCtrls, Controls, ToolsAPI, DesignIntf,
DesignEditors;
{$ELSE}
uses
Windows, Messages, Classes, ExtCtrls, Controls, DsgnIntf, Commctrl;
{$ENDIF}
type
TAbout = class(TPropertyEditor)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
end;
TSizeGripPanel = class(TPanel)
private
FAbout: TAbout;
FUseGrip: Boolean;
FMoving: Boolean;
FSizing: Boolean;
FColorGrip: Boolean;
FOnMove: TNotifyEvent;
FOnSize: TNotifyEvent;
FTop: Integer; { to prevent vertical movement KSG 02.08.01 }
FFreeze: Boolean;
function GetGripRect: TRect;
procedure WMExitSizeMove(var Msg: TMessage); message WM_EXITSIZEMOVE;
procedure SetGripColorStyle(Value: Boolean);
procedure SetGripVisability(Value: Boolean); { KSG 09.10.2001 }
protected
procedure WMNCHitTest(var Msg: TWMNCHitTest); message WM_NCHITTEST;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
override;
procedure WMMove(var Message: TWMMove); message WM_MOVE;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
published
property About: TAbout read FAbout write FAbout;
property FreezeTopAt: Integer read FTop write FTop;
property FreezeTop: boolean read FFreeze write FFreeze;
property ShowGrip: Boolean read FUseGrip write SetGripVisability;
property ColoredGrip: Boolean read FColorGrip write SetGripColorStyle;
property OnMove: TNotifyEvent read FOnMove write FOnMove;
property OnSize: TNotifyEvent read FOnSize write FOnSize;
end;
procedure Register;
implementation
uses Dialogs, SysUtils, Graphics;
procedure TAbout.Edit;
begin
MessageDlg('SizeMovePanel component v1.0.2'#13'by Kevin S. Gallagher',
mtInformation, [mbOK], 0);
end;
function TAbout.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paDialog, paReadOnly];
end;
function TAbout.GetValue: string;
begin
Result := '(about)';
end;
constructor TSizeGripPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
{ Don't care for a caption at all }
ControlStyle := ControlStyle - [csSetCaption];
ShowGrip := True;
FreezeTop := False;
FColorGrip := False;
end;
procedure TSizeGripPanel.WMExitSizeMove(var Msg: TMessage);
begin
inherited;
if FreezeTop then
Top := FTop;
Msg.Result := 0;
end;
procedure TSizeGripPanel.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
const
SC_DRAGMOVE: Longint = $F012;
begin
{ Might also want to check for Client alignment too. }
if (Align = alNone) then
begin
FMoving := True;
ReleaseCapture;
SendMessage(Handle, WM_SYSCOMMAND, SC_DRAGMOVE, 0);
end
else
inherited MouseDown(Button, Shift, X, Y);
end;
procedure TSizeGripPanel.WMMove(var Message: TWMMove);
begin
inherited;
if FMoving then
begin
FMoving := False;
Parent.Realign;
if Assigned(FOnMove) then
FOnMove(Self);
end;
end;
procedure TSizeGripPanel.WMSize(var Message: TWMSize);
begin
inherited;
if FSizing then
begin
FSizing := False;
Parent.Realign;
if Assigned(FOnSize) then
FOnSize(Self);
end;
end;
function TSizeGripPanel.GetGripRect: TRect;
var
GripWidth: integer;
GripHeight: integer;
begin
GripWidth := GetSystemMetrics(SM_CXHSCROLL);
GripHeight := GetSystemMetrics(SM_CYVSCROLL);
Result := GetClientRect();
Result.Left := Result.Right - GripWidth;
Result.Top := Result.Bottom - GripHeight;
end;
procedure TSizeGripPanel.WMNCHitTest(var Msg: TWMNCHitTest);
var
ScreenPt: TPoint;
begin
inherited;
if not (csDesigning in ComponentState) and (Msg.Result = HTCLIENT) then
begin
ScreenPt := ScreenToClient(Point(Msg.Xpos, Msg.Ypos));
if (ScreenPt.x >= GetGripRect.Left) and (ScreenPt.y >= GetGripRect.Top) then
Msg.Result := HTBOTTOMRIGHT;
{ Used to trigger OnSize }
with Msg do
if Result in [Windows.HTLEFT..Windows.HTBOTTOMRIGHT] then
FSizing := True;
end;
end;
procedure TSizeGripPanel.Paint;
var
Rect: TRect;
begin
inherited Paint;
if not FUseGrip then
exit;
Rect := GetGripRect;
if not FColorGrip then
DrawFrameControl(Canvas.Handle, Rect, DFC_SCROLL, DFCS_SCROLLSIZEGRIP)
else
with Self.Canvas do
begin
Brush.Style := bsClear;
Font.Name := 'Marlett';
Font.Size := 8;
Font.Color := clGray;
TextOut(rect.left, rect.top, 'o');
Font.Color := clWhite;
TextOut(rect.left, rect.top, 'p');
end;
end;
procedure TSizeGripPanel.SetGripColorStyle(Value: Boolean);
begin
if Value <> FColorGrip then
begin
FColorGrip := Value;
Repaint;
end;
end;
procedure TSizeGripPanel.SetGripVisability(Value: Boolean);
begin
if Value <> FUseGrip then
begin
FUsegrip := Value;
Repaint;
end;
end;
procedure Register;
begin
RegisterComponents('Samples', [TSizeGripPanel]);
RegisterPropertyEditor(TypeInfo(TAbout), TSizeGripPanel, 'ABOUT', TAbout);
end;
end.
2005. január 31., hétfő
Resize a *.jpg image and save the result to a file (2)
Problem/Question/Abstract:
Before importing an image (jpg) into a database, I would like to resize it (reduce its size) and generate the corresponding smaller file. How can I do this?
Answer:
Load the JPEG into a bitmap, create a new bitmap of the size that you want and pass them both into SmoothResize then save it again ... there's a neat routine JPEGDimensions that gets the JPEG dimensions without actually loading the JPEG into a bitmap, saves loads of time if you only need to test its size before resizing.
{ ... }
type
TRGBArray = array[Word] of TRGBTriple;
pRGBArray = ^TRGBArray;
{ ... }
procedure SmoothResize(Src, Dst: TBitmap);
var
x, y: integer;
xP, yP: integer;
xP2, yP2: integer;
SrcLine1, SrcLine2: pRGBArray;
t3: integer;
z, z2, iz2: integer;
DstLine: pRGBArray;
DstGap: integer;
w1, w2, w3, w4: integer;
begin
Src.PixelFormat := pf24Bit;
Dst.PixelFormat := pf24Bit;
if (Src.Width = Dst.Width) and (Src.Height = Dst.Height) then
Dst.Assign(Src)
else
begin
DstLine := Dst.ScanLine[0];
DstGap := Integer(Dst.ScanLine[1]) - Integer(DstLine);
xP2 := MulDiv(pred(Src.Width), $10000, Dst.Width);
yP2 := MulDiv(pred(Src.Height), $10000, Dst.Height);
yP := 0;
for y := 0 to pred(Dst.Height) do
begin
xP := 0;
SrcLine1 := Src.ScanLine[yP shr 16];
if (yP shr 16 < pred(Src.Height)) then
SrcLine2 := Src.ScanLine[succ(yP shr 16)]
else
SrcLine2 := Src.ScanLine[yP shr 16];
z2 := succ(yP and $FFFF);
iz2 := succ((not yp) and $FFFF);
for x := 0 to pred(Dst.Width) do
begin
t3 := xP shr 16;
z := xP and $FFFF;
w2 := MulDiv(z, iz2, $10000);
w1 := iz2 - w2;
w4 := MulDiv(z, z2, $10000);
w3 := z2 - w4;
DstLine[x].rgbtRed := (SrcLine1[t3].rgbtRed * w1 + SrcLine1[t3 + 1].rgbtRed *
w2 +
SrcLine2[t3].rgbtRed * w3 + SrcLine2[t3 + 1].rgbtRed * w4) shr 16;
DstLine[x].rgbtGreen := (SrcLine1[t3].rgbtGreen * w1 + SrcLine1[t3 +
1].rgbtGreen * w2 +
SrcLine2[t3].rgbtGreen * w3 + SrcLine2[t3 + 1].rgbtGreen * w4) shr 16;
DstLine[x].rgbtBlue := (SrcLine1[t3].rgbtBlue * w1 + SrcLine1[t3 + 1].rgbtBlue
* w2 +
SrcLine2[t3].rgbtBlue * w3 + SrcLine2[t3 + 1].rgbtBlue * w4) shr 16;
inc(xP, xP2);
end;
inc(yP, yP2);
DstLine := pRGBArray(Integer(DstLine) + DstGap);
end;
end;
end;
function LoadJPEGPictureFile(Bitmap: TBitmap; FilePath, Filename: string): boolean;
var
JPEGImage: TJPEGImage;
begin
if (Filename = '') then
{No filename so nothing to load - return false ...}
Result := false
else
begin
try
JPEGImage := TJPEGImage.Create;
try
JPEGImage.LoadFromFile(FilePath + Filename);
Bitmap.Assign(JPEGImage);
Result := true;
finally
JPEGImage.Free;
end;
except
Result := false;
end;
end;
end;
function SaveJPEGPictureFile(Bitmap: TBitmap; FilePath, Filename: string;
Quality: integer): boolean;
begin
Result := true;
try
if ForceDirectories(FilePath) then
begin
with TJPegImage.Create do
begin
try
Assign(Bitmap);
CompressionQuality := Quality;
SaveToFile(FilePath + Filename);
finally
Free;
end;
end;
end;
except
raise;
Result := false;
end;
end;
function JPEGDimensions(Filename: string; var X, Y: Word): boolean;
var
SegmentPos: integer;
SOIcount: integer;
b: byte;
begin
Result := false;
with TFileStream.Create(Filename, fmOpenRead or fmShareDenyNone) do
begin
try
Position := 0;
Read(X, 2);
if (X <> $D8FF) then
exit;
SOIcount := 0;
Position := 0;
while (Position + 7 < Size) do
begin
Read(b, 1);
if (b = $FF) then
begin
Read(b, 1);
if (b = $D8) then
inc(SOIcount);
if (b = $DA) then
break;
end;
end;
if (b <> $DA) then
exit;
SegmentPos := -1;
Position := 0;
while (Position + 7 < Size) do
begin
Read(b, 1);
if (b = $FF) then
begin
Read(b, 1);
if (b in [$C0, $C1, $C2]) then
begin
SegmentPos := Position;
dec(SOIcount);
if (SOIcount = 0) then
break;
end;
end;
end;
if (SegmentPos = -1) then
exit;
if (Position + 7 > Size) then
exit;
Position := SegmentPos + 3;
Read(Y, 2);
Read(X, 2);
X := Swap(X);
Y := Swap(Y);
Result := true;
finally
Free;
end;
end;
end;
2005. január 30., vasárnap
Using SetMapMode during printing
Problem/Question/Abstract:
Printing something is relatively easy with Delphi. But there are times, when you need to use the same functions for drawing on screen canvas and on printer. Did you ever try to? And you got the printer image much smaller, than on the screen, right? That's because you have to change coordinates passed to GDI functions or use SetMapMode function. The article is about how to use this function and a bit more.
Answer:
Suppose you need to draw a rectangle with coordinates ((0,0),(300,300)). On the screen such rectangle will be a bit bigger than one inch (at least on 1024*768 resolution on 15' monitor). But when you call Printer.Canvas.FrameRect(Rect(0, 0, 300, 300)), you get a tiny rectangle with side length of .39 inch.
So, you need to perform transformation of coordinate system before printing.
Open MSDN, see SetMapMode, feel happy. You find, that MM_ANISOTROPIC mode is what you need (remember, that printers have different vertical and horizontal resolution and page size, so you need to use MM_ANISOTROPIC parameter).
SetMapMode(TmpDC, MM_ANISOTROPIC);
// we use TmpDC to prepare an image, that will be later copied to printer
// canvas.
But then you need to call a couple of other functions to do the job.
These functions are SetWindowExtEx and SetViewPortExtEx. As described in documentation, these functions let you set logical and "physical" coordinate systems for device context. What parameters do you have to pass to it?
Logical coordinates is the size of the screen part needed to display an image in WYSIWYG mode (to get the same size as on the screen).
Physical coordinates define the size in pixels of the device media (paper in our case).
We will find the real size of the paper in 0.01 mm. It will be used in further calculations:
// find the width of the printer page
MMWidth := MulDiv(GetDeviceCaps(PrinterDC, PHYSICALWIDTH), 2540,
GetDeviceCaps(PrinterDC, LOGPIXELSX));
// find the height of the printer page
MMHeight := MulDiv(GetDeviceCaps(PrinterDC, PHYSICALHEIGHT), 2540,
GetDeviceCaps(PrinterDC, LOGPIXELSY));
Now you have to set logical coordinates using SetWindowExtEx and physical dimensions of device context (actually, paper size) using SetViewPortExtEx.
SetWindowExtEx(TmpDC, LogExtX, LogExtY, nil);
SetViewPortExtEx(TmpDC, PhExtX, PhExtY, nil);
How do we calculate LogExt* parameters?
ScreenDC := GetDC(0);
// now find logical width of the screen space, needed to display the image in WYSIWYG mode
// Scale parameter is used to provide scaling during printing.
LogExtX := MulDiv(MMWidth, 100 * GetDeviceCaps(ScreenDC, LOGPIXELSX), 2540 * Scale);
// now find logical height of the screen space, needed to display the image in WYSIWYG mode
// Scale parameter is used to provide scaling during printing.
LogExtY := MulDiv(Printer.PageHeight, 100 * GetDeviceCaps(DC, LOGPIXELSY), 2540 *
Scale);
ReleaseDC(0, screenDC);
How do we calculate PhExt* parameters?
PhExtX := MulDiv(Printer.PageWidth, GetDeviceCaps(Printer.PrinterDC, LOGPIXELSX),
2540);
PhExtY := MulDiv(Printer.PageHeight, GetDeviceCaps(Printer.PrinterDC, LOGPIXELSY),
2540);
That's all, folks :). Now you can safely draw the rectangle.
Remember to restore MapMode after you finished drawing (you can save MapMode using GetMapMode function).
2005. január 29., szombat
Combine the co-related functions into one single function
Problem/Question/Abstract:
How to make the same function to return the value you want? How to combine the co-related functions into one single function and Still get the values what all the functions returned ?
Answer:
Let us take the example of the functions which returns the Year, Month, Day, Month name, Day name and the date in a particular format for eg. Britishformat. We have to write a separate functions for returning the desired values. For eg.
function Year(Value: Tdatetime): Word;
var
vY, vM, vD: Word;
begin
DecodeDate(now, vY, vM, vD);
Result := vY;
end;
function Month(Value: Tdatetime): Word;
var
vY, vM, vD: Word;
begin
DecodeDate(now, vY, vM, vD);
Result := vM;
end;
function Day(Value: Tdatetime): Word;
var
vY, vM, vD: Word;
begin
DecodeDate(now, vY, vM, vD);
Result := vD;
end;
function Dayname(Value: Tdatetime): Word;
begin
Result := Formatdatetime('dddd', now);
end;
function Britishformat(Value: Tdatetime): string;
begin
Result := Formatdatetime('dd/mm/yyyy', now);
end;
Since all these functions are related with date, we can combine them into a single function and still get all the values by telling the function what value to return.
For this, first of all we have to declare a record constant, under type section of the unit in which the function is going to reside. Name fields properly as you name the function and the field value to the desired value that you want to return. For eg.
TMyDate = record
Year, Month, Day: Word;
ShortMonthName, LongMonthName, ShortDay, LongDay,
BritishFormat, AmericanFormat,
ItalianFormat, RDBMSFormat: string;
LeapYear: Boolean;
end;
If you are not worried about the return value, then keep all fieldvalues of the record as variant. This will reduce the work load of convertion.
Next make a function declaration , depending on the scope of visibility, under the appropriate section . Lets us name the function as ConvertDate which accepts date as a Tdatetime value and returns the record of TmyDate.
function ConvertDate(Value: Tdatetime): TMyDate;
Now under the implementation section the function would be as given below.
function ConvertDate(Value: Tdatetime): TMyDate;
var
vY, vM, vD: Word;
begin
DecodeDate(Value, vY, vM, vD);
Result.Year := vY;
Result.Month := vM;
Result.Day := vD;
Result.LeapYear := IsLeapYear(vY);
Result.ShortDay := FormatDateTime('ddd', Value);
Result.LongDay := FormatDateTime('dddd', Value);
Result.ShortMonthName := FormatDateTime('mmm', Value);
Result.LongMonthName := FormatDateTime('mmmm', Value);
Result.AmericanFormat := FormatDateTime('yyyy/mm/dd', Value);
Result.ItalianFormat := FormatDateTime('mm-dd-yyyy', Value);
Result.BritishFormat := FormatDateTime('dd/mm/yyyy', Value);
Result.RDBMSFormat := FormatDateTime('dd-mmm-yyyy', Value);
end;
Calling the function.
If you have three variables varYear, varMonth of word and varBritishformat of string into which you want to store the return values of the function. Then
varYear := ConvertDate(now).Year;
varMonth := ConvertDate(now).Month;
varBritishformat := ConvertDate(now).BritishFormat;
Combining the functions will reduce the headace of remembering the different function names, reduce the lines of coding, and its easy to use.
2005. január 28., péntek
My Assertion Handler
Problem/Question/Abstract:
How do you implement your own handler for assertion failures?
Answer:
program AssertDemo;
{
Copyright (c) 2001 by E.J.Molendijk
Delphi Factory Netherlands BV
This little program demonstrates the use
of your own assertion handler.
Check out the AssertErrorHandler() procedure in SysUtils.pas to
see how borland has implemented their (far more complex) handler.
}
uses
Dialogs;
procedure MyAssertErrorHandler(const Message, Filename: string;
LineNumber: Integer; ErrorAddr: Pointer);
begin
ShowMessageFmt(
'This is my own assertion handler for %s line %d: %s',
[Filename, LineNumber, Message]);
// you could save the information to a file or something...
end;
begin
AssertErrorProc := @MyAssertErrorHandler;
assert(false, 'assertion failure test');
end.
2005. január 27., csütörtök
Restore files from the recycle bin and delete files present in the recycle bin
Problem/Question/Abstract:
How to restore files from the recycle bin and delete files present in the recycle bin.
Answer:
To restore as well as delete file from the bin you need to make use of the following functions.
function SHQueryRecycleBin(pszrtootpath: pchar; QUERYRBINFO: pshqueryrbinfo): integer;
stdcall; external 'shell32' name 'SHQueryRecycleBinA';
//used to get the number of files in the bin.
function _FindFirstChangeNotification(lpPathName: PChar; bWatchSubtree: TWinBool;
dwNotifyFilter:
DWORD): THandle; stdcall; external kernel32 name 'FindFirstChangeNotificationA';
// used to notify the program when user has deleted a file
function SHEmptyRecycleBin(hwnd: thandle; pszRootPath: pchar; dwFlags: integer):
integer; stdcall; external 'shell32.dll' name 'SHEmptyRecycleBinA';
//This function empties the recycle bin.
In delphi the function FindFirstChangeNotification is already declared but in Delphi 3 and above it does not work correctly.If the second parameter is true then the function always returns an invalid handle.(visit http://members.aye.net/~bstowers/delphi/bugs/ for more info).
So you need to redeclare the FindFirstChangeNotification function as shown below.
type
TWinBool = (winFalse, winTrue);
function _FindFirstChangeNotification(lpPathName: PChar; bWatchSubtree: TWinBool;
dwNotifyFilter:
DWORD): THandle; stdcall; external kernel32 name 'FindFirstChangeNotificationA';
The above function is used to refresh the list of files in the recyclebin when the user deletes a file.
To use this function we have to first create a thread.This thread checks continuosly checks whether any file was deleted and then refreshes the list of deleted items.
For more information see delphi tips 'SHQUERYBINFO', 'SHemptyrecycleBin',
'Get the list of files from bin'.
Here is the code of the thread.
unit Unit2;
interface
uses
Classes, SysUtils, windows;
type
TFileChangeNotify = class(TThread)
private
protected
procedure Execute; override;
procedure filenotify; //refreshes the list when user has deleted a file.
end;
var
qh1: thandle;
implementation
uses
unit1;
procedure TFileChangeNotify.filenotify;
begin
form1.refreshlist;
end;
procedure TFileChangeNotify.Execute;
var
pdir: pchar;
st: integer;
tmp: boolean;
begin
pdir := 'C:\';
qh1 := 0;
qh1 := _FindFirstChangeNotification(pdir, Twinbool(1),
FILE_NOTIFY_CHANGE_LAST_WRITE);
while true do
begin
st := WaitForSingleObject(qh1, INFINITE);
if st = WAIT_OBJECT_0 then
begin
Synchronize(filenotify);
SHUpdateRecycleBinIcon;
end;
tmp := findnextchangenotification(qh1);
if tmp = false then
Terminate;
end;
end;
end.
You need to add a Tlistview control to your form, and add two columns to it.
Here is the code of main program.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Menus, ComCtrls, unit2; {unit2 is the unit in which the thread resides}
const
SHERB_NOCONFIRMATION = $1;
const
SHERB_NOPROGRESSUI = $2;
const
SHERB_NOSOUND = $4;
type
TWinBool = (winFalse, winTrue);
type
Tfbuf = packed record
data: array[0..255] of char;
u1: array[0..3] of char;
recno: smallint;
u2: array[0..18] of char;
end;
type
SHQUERYRBINFO = packed record
cbSize: integer;
i64Size: int64;
i64NumItems: int64;
end;
pshqueryrbinfo = ^SHQUERYRBINFO;
function SHQueryRecycleBin(pszrtootpath: pchar; QUERYRBINFO: pshqueryrbinfo): integer;
stdcall; external 'shell32' name 'SHQueryRecycleBinA';
function _FindFirstChangeNotification(lpPathName: PChar; bWatchSubtree: TWinBool;
dwNotifyFilter: DWORD): THandle; stdcall; external kernel32 name
'FindFirstChangeNotificationA';
function SHUpdateRecycleBinIcon: integer; stdcall; external 'shell32.dll';
function SHEmptyRecycleBin(hwnd: thandle; pszRootPath: pchar; dwFlags: integer):
integer; stdcall; external 'shell32.dll' name 'SHEmptyRecycleBinA';
type
TForm1 = class(TForm)
RBinList: TListView;
MainMenu1: TMainMenu;
file1: TMenuItem;
View1: TMenuItem;
Refresh1: TMenuItem;
Edit1: TMenuItem;
SelectAll1: TMenuItem;
Restore1: TMenuItem;
N1: TMenuItem;
Delete1: TMenuItem;
N2: TMenuItem;
Close1: TMenuItem;
InvertSelection1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure Refresh1Click(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure file1Click(Sender: TObject);
procedure SelectAll1Click(Sender: TObject);
procedure InvertSelection1Click(Sender: TObject);
procedure Restore1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Close1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Delete1Click(Sender: TObject);
private
{ Private declarations }
public
qh: thandle;
procedure refreshlist;
function updateinfo(fname: string): boolean;
//Makes appropriate changes to the INFO2 file
//present in recycled folder.
procedure Restorefiles; //restores the selected files from the recycle bin.
procedure deletefiles; //deletes the selected files from the recycle bin.
end;
var
Form1: TForm1;
rbinfo: SHQUERYRBINFO;
reccount: integer;
fhandle: integer;
monitorthread: TFileChangeNotify;
implementation
{$R *.DFM}
procedure tform1.deletefiles;
var
i: integer;
sname: string;
dname: string;
begin
monitorthread.Suspend;
for i := 0 to rbinlist.Items.Count - 1 do
begin
if rbinlist.Items[i].Selected = true then
begin
sname := ExtractFileDrive(rbinlist.Items[i].SubItems[0]) + '\Recycled\DC' +
rbinlist.Items[i].SubItems[1] + ExtractFileExt(rbinlist.Items[i].caption);
dname := rbinlist.Items[i].SubItems[0] + rbinlist.Items[i].caption;
deleteFile(sname);
updateinfo(dname);
end;
end;
monitorthread.Resume;
end;
function tform1.updateinfo(fname: string): boolean;
var
rbuff: Tfbuf;
fread: integer;
tsize: integer;
aname: pchar;
ch: char;
begin
result := false;
ch := #0;
fhandle := fileopen('C:\recycled\info2', fmOpenReadWrite or fmShareDenyNone);
if fhandle > 0 then
begin
tsize := GetFileSize(fhandle, nil);
setfilepointer(fhandle, 20, nil, FILE_BEGIN);
fread := 20;
while (fread
begin
fread := fread + fileread(fhandle, rbuff, 280);
if rbuff.data[0] <> #0 then
begin
aname := pchar(@rbuff.data[0]);
if StrComp(aname, pchar(fname)) = 0 then
begin
setfilepointer(fhandle, -280, nil, FILE_CURRENT);
filewrite(fhandle, ch, 1);
result := true;
break;
end;
end;
end;
fileclose(fhandle);
end;
end;
procedure tform1.refreshlist;
var
rbuff: Tfbuf;
fread: integer;
tsize: integer;
aname: pchar;
fitem: tlistitem;
dname: pchar;
iconhandle: thandle;
tmp: word;
iconid: integer;
icon: ticon;
begin
monitorthread.Suspend;
zeromemory(@rbuff, sizeof(rbuff));
rbinlist.Items.Clear;
fhandle := fileopen('C:\recycled\info2', fmOpenRead);
if fhandle > 0 then
begin
tsize := GetFileSize(fhandle, nil);
setfilepointer(fhandle, 20, nil, FILE_BEGIN);
fread := 20;
while (fread
begin
fread := fread + fileread(fhandle, rbuff, 280);
if rbuff.data[0] <> #0 then
begin
aname := pchar(@rbuff.data[0]);
dname := pchar((ExtractFileDrive(aname) + '\Recycled\DC' + inttostr
(rbuff.recno) + extractfileext(aname)));
iconhandle := ExtractAssociatedIcon(HInstance, dname, tmp);
icon.Handle := iconhandle;
iconid := largeimagelist.AddIcon(icon);
fitem := rbinlist.Items.add;
fitem.ImageIndex := iconid;
fitem.Caption := ExtractFileName(aname);
fitem.SubItems.Add(ExtractFilePath(aname));
fitem.SubItems.add(inttostr(rbuff.recno));
end;
end;
fileclose(fhandle);
end;
rbinfo.cbSize := sizeof(rbinfo);
rbinfo.i64NumItems := 0;
rbinfo.i64Size := 0;
SHQueryRecycleBin('C:\', @rbinfo);
if (rbinlist.items.count = 0) and (rbinfo.i64Size <> 0) then
SHEmptyRecycleBin(form1.handle, 'C:\', SHERB_NOCONFIRMATION or
SHERB_NOPROGRESSUI);
monitorthread.resume;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
monitorthread := TFileChangeNotify.Create(false);
end;
procedure TForm1.Refresh1Click(Sender: TObject);
begin
refreshlist;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
rbinlist.width := form1.width - 8;
rbinlist.height := form1.height - 48;
end;
procedure TForm1.file1Click(Sender: TObject);
begin
if rbinlist.SelCount > 0 then
begin
restore1.enabled := true;
Delete1.enabled := true;
end
else
begin
restore1.enabled := false;
Delete1.enabled := false;
end;
end;
procedure TForm1.SelectAll1Click(Sender: TObject);
var
i: integer;
begin
for i := 0 to rbinlist.Items.Count - 1 do
rbinlist.Items[i].Selected := true;
end;
procedure TForm1.InvertSelection1Click(Sender: TObject);
var
i: integer;
begin
for i := 0 to rbinlist.Items.Count - 1 do
rbinlist.Items[i].Selected := not (rbinlist.Items[i].Selected);
end;
procedure tform1.Restorefiles;
var
i: integer;
sname: string;
dname: string;
begin
monitorthread.Suspend;
for i := 0 to rbinlist.Items.Count - 1 do
begin
if rbinlist.Items[i].Selected = true then
begin
sname := ExtractFileDrive(rbinlist.Items[i].SubItems[0]) + '\Recycled\DC' +
rbinlist.Items[i].SubItems[1] + ExtractFileExt(rbinlist.Items[i].caption);
dname := rbinlist.Items[i].SubItems[0] + rbinlist.Items[i].caption;
MoveFile(pchar(sname), pchar(dname));
updateinfo(dname);
end;
end;
monitorthread.Resume;
end;
procedure TForm1.Restore1Click(Sender: TObject);
begin
restorefiles;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if qh <> INVALID_HANDLE_VALUE then
FindCloseChangeNotification(qh);
monitorthread.Terminate;
end;
procedure TForm1.Close1Click(Sender: TObject);
begin
form1.close;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
refreshlist;
end;
procedure TForm1.Delete1Click(Sender: TObject);
begin
deletefiles;
end;
end.
2005. január 26., szerda
Save your window size and position
Problem/Question/Abstract:
It's often useful to remember the size and state of your program's window (or sometimes of dialogue boxes) between executions. This article discusses how.
Answer:
The method we're going to use is to save the position in the registry.
First of all, decide where you're going to keep the information. It's customary for apps to place information that varies between users in
HKEY_CURRENT_USER\Software\MyCompany\MyProgram\X.X
(X.X is the version number of the program). We'll use such a key in this article.
You can save the window's current position and size when the program is closing down - the OnDestroy form event handler is a good place for this. The program then restores it's position from the registry (if it's been written yet) when opening - we use the form's OnCreate handler for that code.
There are complications when saving and restoring the window state because of when the window is minimised, Delphi doesn't minimise the form - it hides it and displays the Application window in the taskbar. The method I've used causes a previously minimised window to flash on-screen briefly. I'd welcome ideas on any alternative approaches. (This has now been fixed -- see the component available for download).
Another complication is that when a window is maximised Delphi updates the Width, Height, Left and Top properties of the form to the window's maximised size and position. This means that closing a maximised window stores the maximised size in the registry. When the program is run again it appears maximised, but when the user restores it they expect it to go to the previous normal size and position, but if we reloaded the Left, Top, Height and Width properties, the form won't shrink when restored. We get round this by using the Windows API to get the non-maximised size.
Here's the code - the comments should explain what's happening.
const
CRegKey = 'Software\Demos\WdwStateDemo\1.0';
// Helper function to read registry values, and deal with
// cases where no values exist
function ReadIntFromReg(Reg: TRegistry; Name: string;
Def: Integer): Integer;
{Reads integer with given name from registry and returns it
If no such value exists, returns Def default value}
begin
if Reg.ValueExists(Name) then
Result := Reg.ReadInteger(Name)
else
Result := Def;
end;
procedure TForm1.FormDestroy(Sender: TObject);
var
Reg: TRegistry; // the registry
State: Integer; // state of wdw
Pl: TWindowPlacement; // used for API call
R: TRect; // used for wdw pos
begin
{Calculate window's normal size and position using
Windows API call - the form's Width, Height, Top and
Left properties will give maximized window size if
form is maximised, which is not what we want here}
Pl.Length := SizeOf(TWindowPlacement);
GetWindowPlacement(Self.Handle, @Pl);
R := Pl.rcNormalPosition;
Reg := TRegistry.Create;
try
// Open required key - and create it if it doesn't exist
Reg.RootKey := HKEY_CURRENT_USER;
Reg.OpenKey(CRegKey, True);
// Write window size and position
Reg.WriteInteger('Width', R.Right - R.Left);
Reg.WriteInteger('Height', R.Bottom - R.Top);
Reg.WriteInteger('Left', R.Left);
Reg.WriteInteger('Top', R.Top);
// Write out state of window
{Record window state (maximised, minimised or normal)
- special case when minimized since form window is simply
hidden when minimised, and application window is actually
the one minimised - so we check to see if application
window *is* minimized and act accordingly}
if IsIconic(Application.Handle) then
{minimized - write that state}
State := Ord(wsMinimized)
else
{not mimimized - we can rely on window state of form}
State := Ord(Self.WindowState);
Reg.WriteInteger('State', State);
finally
Reg.Free;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
Reg: TRegistry; // the registry
State: Integer; // state of wdw
begin
Reg := TRegistry.Create;
try
// Open required key - and exit if it doesn't exist
Reg.RootKey := HKEY_CURRENT_USER;
if not Reg.OpenKey(CRegKey, False) then
Exit;
// Read the window size and position
// - designed form sizes are defaults
Self.Width := ReadIntFromReg(Reg, 'Width', Self.Width);
Self.Height := ReadIntFromReg(Reg, 'Height', Self.Height);
Self.Left := ReadIntFromReg(Reg, 'Left', Self.Left);
Self.Top := ReadIntFromReg(Reg, 'Top', Self.Top);
// Now get window state and restore
State := ReadIntFromReg(Reg, 'State', Ord(wsNormal));
{check if window was minimised - we have special
processing for minimized state since Delphi doesn't
minimize windows - it uses application window
instead}
if State = Ord(wsMinimized) then
begin
{we need to set visible true else form won't restore
properly - but this causes a brief display of form
any ideas on how to stop this?}
Self.Visible := True;
Application.Minimize;
end
else
Self.WindowState := TWindowState(State);
finally
Reg.Free;
end;
end;
A component that wraps up all this functionality on behalf of the form it lives on is available for download. There's also a sister component included that works with ini files rather than the registry.
Component Download: http://www.delphidabbler.com/download.php?file=pjwdwstate.zip
2005. január 25., kedd
Creating an Insertable ActiveX control for Microsoft Office
Problem/Question/Abstract:
How to create an ActiveX control for Microsoft Office that is "Insertable"
Answer:
There is a nice feature in Microsoft Word that allows you to put ActiveX controls onto a Word document. To do so you go to the Insert Menu, and click Object…. This displays a dialog list a number of "Insertable" controls.
There is one problem with this dialog though; there is no browse button and no obvious method of adding your control to the list. So how do you do it?
Turns out your ActiveX control is missing one registry entry, and the Type Library editor does not give you the option of inserting it. The entry is “Insertable” (and you’ve been wondering why I have been using that word so much). The key goes in the HKEY_CLASSES_ROOT section of the registry under a key that is your ActiveX control’s class id.
In the end, your registry should look something like this:
HKEY_CLASSES_ROOT->YourControl.TheClass->Insertable
Now, you can either go into RegEdit and enter this manually (a good way to make sure I’m not lying through my teeth), or you can add this entry automatically when the control is registered. Ya, I thought so, option number 2 it is:
So, if you want this to be put in the registry automatically...
Go to the unit containing your automation object.
Make sure Registry and Windows are in your uses statement.
Modify your INITIALIZATION section to something like this with a new function:
procedure MoreKeys;
const
C_KEY: string = 'YourControl.TheClass'; // your controls class ID
var
oReg: TRegistry;
begin
oReg := TRegistry.Create;
try
oReg.OpenKey(HKEY_CLASSES_ROOT);
// the true mean create the key if it doesn’t exist
oReg.OpenKey(C_Key + '\Insertable', True);
finally
oReg.CloseKey;
oReg.Free;
end;
end;
initialization
TActiveFormFactory.Create(
ComServer,
TActiveFormControl,
...yada, yada, yada);
MoreKeys;
end.
2005. január 24., hétfő
Towards a more accurate sort order in MSSQL7
Problem/Question/Abstract:
Sorting Addresses is a pain at the best of times, especially when a client supplies bad data (You may define clear fields in your DB, but when the data comes in, does it fit easily??)
This attempts to resolve this issue for MSSQL Server
Answer:
Wherever you keep the addresses, add a field SortOrder (real)
Whenever the Address changes, update the new value using this stored procedure to calculate the value.
Using the server to do the work will cut out network traffic, etc.
It can be called to update using something like this.
---
DECLARE @Addr varchar(100),@SortIndex real
SET @Addr=(SELECT ISNULL(Addr1+' ','')+ISNULL(Addr2+' ','')+ISNULL(Addr3+' ','')+ISNULL(Addr4+' ','')+ISNULL(Addr5+' ','')+ISNULL(PCode,'') FROM Main WHERE ID=@Main_ID)
EXEC spCalcSortIndex @Addr,@Index=@SortIndex OUTPUT
UPDATE Main
SET SortIndex=@SortIndex
WHERE ID=@Main_ID
---
Here is the Complete Stored Procedure to copy and paste in:
---
Create Procedure "spCalcSortIndex" @NumStr varchar(100)='',@Index real OUTPUT
AS
/*This will return a sort index based on the @NumStr passed
Call as: DECLARE @Value_I_Want real
EXEC spCalcSortIndex (SELECT AddressFields FROM Addresses WHERE ID=x),@Index=@Value_I_Want OUTPUT*/
DECLARE @strlen int,@i int,@j int
DECLARE @found bit
DECLARE @numpart real,@strpart real, @divisor real
DECLARE @ChoppedStr varchar(100)
SET @strlen=LEN(@NumStr)
IF @strlen=0
BEGIN
SET @Index=0
RETURN
END
/*Split the string into a 'number' and a 'string' part*/
/*Initialise*/
SELECT @found=0, @ChoppedStr=@NumStr,@numpart=0,@i=1
/*Locate the first digit*/
WHILE @i<=@strlen
BEGIN
IF SUBSTRING(@NumStr,@i,1) IN ('0','1','2','3','4','5','6','7','8','9')
BEGIN
SET @found=1
BREAK
END
SET @i=@i+1
END
IF @found=1
BEGIN
/*now get the remaining digits*/
SELECT @found=0,@j=@i
WHILE @j<=@strlen
BEGIN
IF SUBSTRING(@NumStr,@j,1) NOT IN ('0','1','2','3','4','5','6','7','8','9')
BEGIN
SET @found=1
BREAK
END
SET @j=@j+1
END
/*Separate out the string parts*/
IF @found=1
BEGIN
/*Number was embedded..*/
SELECT @numpart=CONVERT(real,SUBSTRING(@NumStr,@i,@j-@i)),
@ChoppedStr=LEFT(@Numstr,@i-1)+RIGHT(@NumStr,@strlen-@j+1)
END
ELSE
BEGIN
/*Number went to the end of the string*/
SELECT @numpart=CONVERT(real,SUBSTRING(@NumStr,@i,@strlen)),
@ChoppedStr=LEFT(@Numstr,@i-1)
END
END
SET @Choppedstr=UPPER(LTRIM(RTRIM(@ChoppedStr)))
SET @strlen=LEN(@ChoppedStr)
/*Evaluate a Number for the remaining part of the string*/
SELECT @strpart=0,@divisor=1,@i=1
WHILE @i<=@strlen
BEGIN
SET @divisor=@divisor/256
SET @strpart=@strpart+(ASCII(SUBSTRING(@ChoppedStr,@i,1))*@divisor)
SET @i=@i+1
END
/*All done, return the value*/
SET @Index=@numpart+@strpart
---
2005. január 23., vasárnap
AlphaBlend your forms with a component
Problem/Question/Abstract:
Do you like the AlphaBlending of Windows 2000/XP menus, panels and other visual components? Use that and you'll implement in your applications.
Answer:
unit uAlphaWindow;
interface
uses
Windows, Messages, Classes, Controls, Forms;
type
TAlphaPercent = 0..100;
TAlphaWindow =
class(TComponent)
protected
User32: HModule;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetTransparentHWND(HWnd: THandle; Percent: TAlphaPercent);
procedure SetTransparent(Percent: TAlphaPercent);
procedure SetOpaqueHWND(HWnd: THandle);
procedure SetOpaque;
end;
procedure Register;
implementation
const
LWA_ALPHA = $2;
GWL_EXSTYLE = -20;
WS_EX_LAYERED = $80000;
WS_EX_TRANSPARENT = $20;
var
SetLayeredWindowAttributes: function(HWnd: LongInt; crKey: Byte; bAlpha: Byte;
dwFlags: LongInt): LongInt; StdCall;
constructor TAlphaWindow.Create(AOwner: TComponent);
begin
inherited;
User32 := LoadLibrary('USER32.DLL');
if (User32 <> 0) then
@SetLayeredWindowAttributes := GetProcAddress(User32, 'SetLayeredWindowAttributes')
else
SetLayeredWindowAttributes := nil;
end;
destructor TAlphaWindow.Destroy;
begin
if (User32 <> 0) then
FreeLibrary(User32);
inherited;
end;
procedure TAlphaWindow.SetOpaqueHWND(HWnd: THandle);
var
Old: THandle;
begin
if (IsWindow(HWnd)) then
begin
Old := GetWindowLongA(HWnd, GWL_EXSTYLE);
SetWindowLongA(HWnd, GWL_EXSTYLE, Old and ((not 0) - WS_EX_LAYERED));
end;
end;
procedure TAlphaWindow.SetOpaque;
begin
Self.SetOpaqueHWND((Self.Owner as TWinControl).Handle);
end;
procedure TAlphaWindow.SetTransparentHWND(HWnd: THandle; Percent: TAlphaPercent);
var
Old: THandle;
begin
if ((User32 <> 0) and (Assigned(SetLayeredWindowAttributes)) and (IsWindow(HWnd)))
then
if (Percent = 0) then
SetOpaqueHWND(HWnd)
else
begin
Percent := 100 - Percent;
Old := GetWindowLongA(HWnd, GWL_EXSTYLE);
SetWindowLongA(HWnd, GWL_EXSTYLE, Old or WS_EX_LAYERED);
SetLayeredWindowAttributes(HWnd, 0, (255 * Percent) div 100, LWA_ALPHA);
end;
end;
procedure TAlphaWindow.SetTransparent(Percent: TAlphaPercent);
begin
Self.SetTransparentHWND((Self.Owner as TForm).Handle, Percent);
end;
procedure Register;
begin
RegisterComponents('Christian', [TAlphaWindow]);
end;
end.
Example:
tAlphaWindow1.SetTransparent;
or use this:
tAlphaWindow1.SetTransparent(50);
2005. január 22., szombat
Using the Affinity Mask in multi-CPU environments
Problem/Question/Abstract:
When writing applications that are designated to tun in multi-CPU environments, it is very useful to be able to control which CPU's the application executes on. By optimizing the CPU usage one can dramatically increase the performance of the application
Answer:
Introduction
When writing applications that are designated to tun in multi-CPU environments, it is very useful to be able to control which CPU's the application executes on.
By optimizing the CPU usage one can dramatically increase the performance of the application.
Affinity Masks - Background
When a process is created in windows, an affinity mask is passed to it. This is usually the system affinity mask, since the system is launching the process.
Also by default each thread created by this process is now assigned the current affinity mask for the process. This means that the thread is executed in any of the available CPU's.
If the "Process Affinity Mask" is changed, all threads created after that will only be allowed to execute in any of the available CPU's, also the whole process is limited to the same CPU's.
Getting the Affinity Mask
Windows provides us with an API call that help us get the affinity mask.
The API call is:
GetProcessAffinityMask(hProcess: Cardinal; var procAFMask, sysAFMask);
The hProcess parameter is the current process handle, and the procAFMask and sysAFMask variables are cardinals.
Before we change the affinity mask, we first need to get the current affinity mask for the whole system. This is because we do not want to try to set an affinity mask that is not possible.
When the API call returns it puts the BitMASK for the CPU's in each of the parameters.
The bits are encoded as followes:
BitMask
CPU's
00000001
1st CPU
00000010
2nd CPU
00000100
3rd CPU
00001000
4th CPU
00010000
5th CPU
00100000
6th CPU
01000000
7th CPU
10000000
8th CPU
By combining these BIT values one can determine the CPU count/mask. The BitMask is 32 bits in size, so theoretically the BitMask supports up to 32 CPU's.
Example: BitMask=00000011 would mean 2 CPU's, number 1 and 2.
Changing the Affinity Mask of a Process
Windows provides us with an API call that help us set the affinity mask.
The API call is:
SetProcessAffinityMask(hprocess: Cardinal; ProcessAffinityMask: Cardinal);
The hProcess parameter is the current process handle, and the ProcessAffinityMask variable is a cardinal.
To obtain the current process handle we need another API call named "GetCurrentProcess()". This API call returns the handle of the current process.
The ProcessAffinityMask variable contains the BitMASK of the CPU's we want this process to execute on. (see the BitMask table above).
Example:
var
ProcAFMask,
SysAFMask: Cardinal;
begin
{ Get the current values }
GetProcessAffinityMask(GetCurrentProcess, ProcAFMask, SysAFMask);
{ Manipulate }
SysAFMAsk := $00000001; // Set this process to run on CPU 1 only
{ Set the Process Affinity Mask }
SetProcessAffinityMask(GetCurrentProcess, SysAFMAsk);
end;
A realworld example
Now that I have shown how to get and set the affinity masks for processes, I'd like to show a real-world example of how to utilize this.
I had a situation where our customer had a 4 CPU server, and used it for some heavy processing about 80% of the time.
The customer wanted us to create an application for them, but they didn't want to invest in the hardware, since they already had a good server running. They where unsure of the total load on the server so we investigated, and found that the server only used the 2 first CPU's when under heavy load. This meant that there were 2 CPU's available for us !
So we implemented the Affinity Mask API calls, and concluded that our application was executing nicely on CPU's number 3 and 4 only, leaving the 2 other CPU's free for the other application on the server.
Our application used alot of Threads, but since the master affinity for the whole process was changed, the threads followed the set parameters without problems.
What about the affinity masks for the Threads?
If you want to read more about the affinity masks for Threads there is an excellent article:
Extending TThread for multiple processor environments
2005. január 21., péntek
Send compless strings (all 256 ASCII) to an ASP page
Problem/Question/Abstract:
Ever needed to send compless strings, that contains ASCII values that will be truncated from the HTTP protocol, to an ASP page?
I did, but I found a solution and there it's..
Answer:
Just convert the complete string to a hexadecimal value with this function...
function CharsToPrintable(What: string): string;
var
IdX: Integer;
tmpStr, outStr: string;
begin
Result := '';
outStr := '';
tmpStr := What;
for IdX := 1 to Length(tmpStr) do
outStr := outStr + IntToHex(StrToInt(tmpStr[IdX]), 2);
Result := outStr;
end;
..and then reconvert it to the original string, taking 2 chars at time and calculating the original ASCII value (byte) with this ASP code (works correctly in Visual Basic, but I have not yet tested with ASP (will try soon)):
Private Function GetFromHexValue(Da As String) As String
Dim Ai As Integer
Dim Bi As Integer
If IsNumeric(Left(Da, 1)) Then
Ai = CInt(Left(Da, 1))
Else
Ai = Asc(UCase(Left(Da, 1))) - 65
End If
If IsNumeric(Right(Da, 1)) Then
Bi = CInt(Right(Da, 1))
Else
Bi = Asc(UCase(Right(Da, 1))) - 55
End If
GetFromHexValue = Chr(Ai * 16 + Bi)
End Function
...and...
Dim X As Integer
Dim A As String
Dim Inputed As String
Inputed = ""
For X = 1 To Len(Request.QueryString("MyString")) Step 2
If X > Len(Request.QueryString("MyString")) Then Exit For
A = Mid(Request.QueryString("MyString"), X, 2)
Inputed = Inputed + GetFromHexValue(A)
Next X
Response.Write Inputed
2005. január 20., csütörtök
Add style to your application implementing an easter egg
Problem/Question/Abstract:
Many world class applications implement some easter egg to give its author(s) credit, so why not to use this feature in your own applications?
Answer:
An easter egg is some piece of code that executes only when the user uses some special keystrokes, they are used frequently to give credit to the author(s) of some program.
For example in Delphi�s About box hold Shift + Alt and then type "team", you will expose an easter egg giving credit to Delphi Staff.
To create your own easter egg take this steps:
1.- Start a new Project
2.- Create the following private fields:
private
FEgg: string;
FCount: Integer;
FCount holds a count of Keystrokes.
FEgg holds the Keystrokes string.
3.- Create two constants
const
EE_CONTROL: TShiftState = [ssCtrl, ssAlt];
EASTER_EGG = 'SECRET';
EE_CONTROL contains the control keys that must be down when the user types the EASTER_EGG string
4.- In the OnCreate event of the form write
procedure TForm1.FormCreate(Sender: TObject);
begin
FCount := 1;
FEgg := EASTER_EGG;
end;
5.- In the OnKeyDown event of the form write
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
//Are the correct control keys down?
if Shift = EE_CONTROL then
begin
//was the proper key pressed?
if Key = Ord(FEgg[FCount]) then
begin
//was this the last keystroke in the sequence?
if FCount = Length(FEgg) then
begin
//Code of the easter egg
ShowMessage('Add your own code here!');
//failure - reset the count
FCount := 1; {}
end
else
begin
//success - increment the count
Inc(FCount);
end;
end
else
begin
//failure - reset the count
FCount := 1;
end;
end;
end;
6.- Finally set the Form�s KeyPreview property to true.
Now you just have to replace the ShowMessage with Something more creative, use your imagination!
Feliratkozás:
Bejegyzések (Atom)