2007. augusztus 14., kedd
How to get the printer port name
Problem/Question/Abstract:
How to get the printer port name
Answer:
Getting the printer port name:
{ ... }
uses
printers, winspool;
function GetCurrentPrinterHandle: THandle;
const
Defaults: TPrinterDefaults = (pDatatype: nil; pDevMode: nil; DesiredAccess:
PRINTER_ACCESS_USE or PRINTER_ACCESS_ADMINISTER);
var
Device, Driver, Port: array[0..255] of char;
hDeviceMode: THandle;
begin
Printer.GetPrinter(Device, Driver, Port, hDeviceMode);
if not OpenPrinter(@Device, Result, @Defaults) then
RaiseLastWin32Error;
end;
procedure TForm1.Button1Click(Sender: TObject);
procedure Display(const prefix: string; S: PChar);
begin
memo1.lines.add(prefix + string(S));
end;
var
pInfo: PPrinterInfo2;
bytesNeeded: DWORD;
hPrinter: THandle;
i: Integer;
begin
for i := 0 to printer.Printers.Count - 1 do
begin
Printer.PrinterIndex := i;
hPrinter := GetCurrentPrinterHandle;
try
GetPrinter(hPrinter, 2, nil, 0, @bytesNeeded);
pInfo := AllocMem(bytesNeeded);
try
GetPrinter(hPrinter, 2, pInfo, bytesNeeded, @bytesNeeded);
Display('ServerName: ', pInfo^.pServerName);
Display('PrinterName: ', pInfo^.pPrinterName);
Display('ShareName: ', pInfo^.pShareName);
Display('PortName: ', pInfo^.pPortName);
finally
FreeMem(pInfo);
end;
finally
ClosePrinter(hPrinter);
end;
end;
end;
2007. augusztus 13., hétfő
How to do a text search in a TMemoField
Problem/Question/Abstract:
How to do a text search in a TMemoField
Answer:
Here is an example of how to search a memo field. The field skills is a memo field:
procedure tdmdistbt.ANDFindSkills(SkillList, PeopleList: TStrings);
var
I, h, foundcount: Integer;
Skills: string;
begin
peoplelist.clear;
with tblTeamMember do
begin
first;
for I := 1 to recordcount do
begin
foundcount := 0;
Skills := uppercase(tblTeamMember.fieldbyname('Skills').asstring);
for h := 0 to skilllist.count - 1 do
begin
if Pos(uppercase(Skilllist[h]), Skills) > 0 then
inc(foundcount, 1);
end;
if foundcount = skilllist.count then
PeopleList.add(tblTeamMemberFullName.value);
next;
end;
end;
end;
2007. augusztus 12., vasárnap
Give Your Forms a Background
Problem/Question/Abstract:
Web pages use tiled bitmaps to create backgrounds. Is it possible to do this in Delphi?
Answer:
Before I learned how to do this, to create a background on a form, I'd drop a TImage on my form, then set its Align property to alClient. For low-resolution bitmaps, the pixelation that would occur at times was absolutely terrible! But with the method that I'll show you here (Note: this is merely ONE way of doing it), you can easily tile bitmaps on the surface of your form. The trick is in trapping the WM_ERASEBKGND message in a handler, creating a bitmap at runtime, then writing a quick bit of code in the OnPaint event handler. Let's go through the steps.
1. In the private section of your code place the following:
private
{ Private declarations }
MyBitmap: TBitmap;
procedure WMEraseBkgnd(var m: TWMEraseBkgnd);
�� message WM_ERASEBKGND;
Notice the declaration of MyBitmap. We'll be creating an instance for it below. The message handler for WM_ERASEBKGND looks like this:
procedure TBmpform.WMEraseBkgnd(var m: TWMEraseBkgnd);
begin
� m.Result := LRESULT(False);
end;
2. Then, create the following code for the OnPaint event handler Note: In the original article, the "x := x + MyBitmap.Width" is a bit inefficient in that continuously accessing the Bitmap.Width or .Height properties can slow things down - especially when you've got code in the OnPaint method. So what I did here was to simply set a couple of variables to store the Width and Height property values of the bitmap.
procedure TBmpForm.FormPaint(Sender: TObject);
var
x, y: Integer;
iBMWid, iBMHeight: Integer;
begin
iBMWid := MyBitmap.Width;
iBMHeight := MyBitmap.Height;
y := 0;
while y < Height do
begin
x := 0;
while x < Width do
begin
Canvas.Draw(x, y, MyBitmap);
x := x + iBMWid;
end;
y := y + iBMHeight;
end;
end;
3. Finally, create an instance of the bitmap you want to tile in the background in the OnCreate event of your form:
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnHint := ShowHint;
MyBitmap := TBitmap.Create;
MyBitmap.LoadFromFile('Brick4.bmp');
end;
4. Whoops, almost forgot! You need to destroy the bitmap when you exit!
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
bmpBackground.Free;
end;
Well, that's it. Don't you just love the quick and dirty ones?
2007. augusztus 11., szombat
Assign a password to a Paradox table
Problem/Question/Abstract:
Assign a password to a Paradox table
Answer:
To assign a password to a Paradox table, use the following unit and call function TablePasswort like this:
uses Unit2;
// ..
TablePasswort(Table1, 'secret');
unit Unit2;
interface
uses
BDE, SysUtils, DBTables, Windows;
function TablePasswort(var table: TTable; password: string): Boolean;
implementation
function StrToOem(const AnsiStr: string): string;
begin
SetLength(result, Length(AnsiStr));
if Length(result) > 0 then
CharToOem(PChar(AnsiStr), PChar(result))
end;
function TablePasswort(var table: ttable; password: string): Boolean;
var
pTblDesc: pCRTblDesc;
hDb: hDBIDb;
begin
result := false;
with table do
begin
if Active and (not Exclusive) then
Close;
if (not Exclusive) then
Exclusive := true;
if (not Active) then
Open;
hDb := DBHandle;
Close
end;
GetMem(pTblDesc, sizeof(CRTblDesc));
FillChar(pTblDesc^, sizeof(CRTblDesc), 0);
with pTblDesc^ do
begin
StrPCopy(szTblName, StrToOem(table.tablename));
szTblType := szParadox;
StrPCopy(szPassword, StrToOem(password));
bPack := true;
bProtected := true
end;
if DbiDoRestructure(hDb, 1, pTblDesc, nil, nil, nil, false) <> DBIERR_NONE then
exit;
if pTblDesc <> nil then
FreeMem(pTblDesc, sizeof(CRTblDesc));
result := true
end;
end.
2007. augusztus 10., péntek
Fake the caption bar of a borderless form
Problem/Question/Abstract:
How to fake the caption bar of a borderless form
Answer:
procedure TForm1.FormPaint(Sender: TObject);
var
r: TRect;
begin
r := Clientrect;
DrawEdge(canvas.handle, r, EDGE_RAISED, BF_RECT or BF_ADJUST);
r.bottom := r.top + GetSystemMetrics(SM_CYCAPTION);
DrawCaption(self.handle, canvas.handle, r, DC_ACTIVE or DC_ICON or DC_TEXT);
InflateRect(r, -2, -2);
r.Left := r.right - GetSystemMetrics(SM_CXSIZE) + 2;
DrawFrameControl(canvas.handle, r, DFC_CAPTION, DFCS_CAPTIONCLOSE);
r.right := r.left - 2;
r.Left := r.right - GetSystemMetrics(SM_CXSIZE) + 2;
DrawFrameControl(canvas.handle, r, DFC_CAPTION, DFCS_CAPTIONMAX);
r.right := r.left;
r.Left := r.right - GetSystemMetrics(SM_CXSIZE) + 2;
DrawFrameControl(canvas.handle, r, DFC_CAPTION, DFCS_CAPTIONMIN);
end;
2007. augusztus 9., csütörtök
How to get a zoomed preview of a full-size TScrollBox
Problem/Question/Abstract:
I have a TScrollBox. In it are between 10 to 300 other components (TCustomControls and TGraphic descendants) which are moveable and resizeable. For a better overview of the large scrollbox workspace I would like to write a small zoombox component showing an overview of the whole workspace in a small 50x50 pixel (or whatever size) area. Is there any easy Windows function for doing this fast? Or do I have to write an own routine?
Answer:
You have to write your own. Following is a little example that shows a 50% reduced preview of the full scrollbox. The controls edit1, edit2, shape1, shape2, image1, memo1 are all on the scrollbox, image2 is used for the preview, button1 triggers the painting of the preview. The main problem here is the way I use to paint a TWinControl owned by the scrollbox. The WM_PRINT message used is supported by all standard and common Windows controls, but not by pure VCL controls like TPanel or the grid classes. For those you may have to use WM_PAINT instead, or the PaintTo method.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
ScrollBox1: TScrollBox;
Edit1: TEdit;
Edit2: TEdit;
Image1: TImage;
Shape1: TShape;
Shape2: TShape;
Memo1: TMemo;
Image2: TImage;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure PaintControl(aControl: TWinControl; aCanvas: TCanvas; offsetx, offsety: Integer);
begin
SaveDC(aCanvas.handle);
try
SetWindowOrgEx(aCanvas.handle, -(acontrol.left + offsetx), -(acontrol.top + offsety), nil);
acontrol.perform(WM_PRINT, acanvas.handle, PRF_CHILDREN or PRF_CLIENT or
PRF_NONCLIENT or PRF_ERASEBKGND);
finally
RestoreDC(aCanvas.handle, -1);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
bmp: TBitmap;
i: integer;
begin
bmp := TBitmap.Create;
try
bmp.width := scrollbox1.HorzScrollBar.Range div 2;
bmp.height := scrollbox1.VertScrollBar.Range div 2;
bmp.canvas.lock;
SetMapMode(bmp.canvas.handle, MM_ISOTROPIC);
SetWindowExtEx(bmp.canvas.handle, 200, 200, nil);
SetViewportExtEx(bmp.canvas.handle, 100, 100, nil);
try
SetWindowOrgEx(bmp.canvas.handle, -scrollbox1.HorzScrollBar.Position,
-scrollbox1.VertScrollBar.POsition, nil);
scrollbox1.perform(WM_PAINT, bmp.canvas.handle, 1);
SetWindowOrgEx(bmp.canvas.handle, 0, 0, nil);
for i := 0 to scrollbox1.controlcount - 1 do
if scrollbox1.controls[i] is TWincontrol then
Paintcontrol(TWincontrol(scrollbox1.Controls[i]), bmp.canvas,
scrollbox1.horzscrollBar.Position, scrollbox1.vertScrollBar.Position);
finally
bmp.canvas.unlock;
end;
image2.picture.bitmap := bmp;
finally
bmp.free;
end;
end;
end.
2007. augusztus 8., szerda
How to change the appearance of the focus rectangle in a TDBGrid
Problem/Question/Abstract:
I would like to be able to change the colour of the focus rectangle for certain cells and also to prevent it from being drawn for certain cells even when they have focus - is this possible? I have a graphic displayed in a column and I don't want it to be obscured by the blue focus rectangle - a transparent focus rectangle would be ok.
Answer:
procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect;
Field: TField; State: TGridDrawState);
var
x: string;
begin
if Field.value = Null then
x := ''
else
x := FloatToStr(field.value);
with Sender as TDbGrid do
begin
if gdFocused in State then
begin
Canvas.Brush.Color := clYellow;
Canvas.Font.color := ClBlack;
end;
Canvas.FillRect(Rect);
Canvas.TextOut(Rect.Left + Canvas.Font.Size, Rect.Top + 2, x);
if gdFocused in State then
Canvas.DrawFocusRect(Rect);
end;
end;
2007. augusztus 7., kedd
Determine the type of an EXE file
Problem/Question/Abstract:
Determine the type of an EXE file
Answer:
Here's a function to return the platform the executable was designed for (16/32 bit Windows or DOS). Read the comment for the usage. This function works as well with DLLs, COMs, and maybe others. Thanks to Peter Below for this code.
Use it as shown at the bottom of the code snippet.
//-------------------------------------------------------------------------
// function to return the type of executable or dll (DOS, 16-bit, 32-bit).
//-------------------------------------------------------------------------
type
TExeType = (etUnknown, etDOS, etWinNE {16-bit}, etWinPE {32-bit});
function GetExeType(const FileName: string): TExeType;
var
Signature,
WinHdrOffset: Word;
fexe: TFileStream;
begin
Result := etUnknown;
try
fexe := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
fexe.ReadBuffer(Signature, SizeOf(Signature));
if Signature = $5A4D { 'MZ' } then
begin
Result := etDOS;
fexe.Seek($18, soFromBeginning);
fexe.ReadBuffer(WinHdrOffset, SizeOf(WinHdrOffset));
if WinHdrOffset >= $40 then
begin
fexe.Seek($3C, soFromBeginning);
fexe.ReadBuffer(WinHdrOffset, SizeOf(WinHdrOffset));
fexe.Seek(WinHdrOffset, soFrombeginning);
fexe.ReadBuffer(Signature, SizeOf(Signature));
if Signature = $454E { 'NE' } then
Result := etWinNE
else if Signature = $4550 { 'PE' } then
Result := etWinPE;
end;
end;
finally
fexe.Free;
end;
except
end;
end;
begin
case GetExeType(aFileName) of
etUnknown: Label3.Caption := 'Unknown file type';
etDOS: Label3.Caption := 'DOS executable';
etWinNE: {16-bit} Label3.Caption := 'Windows 16-bit executable';
etWinPE: {32-bit} Label3.Caption := 'Windows 32-bit executable';
end;
end;
2007. augusztus 6., hétfő
How to create a TScrollBox with an own background
Problem/Question/Abstract:
How to create a TScrollBox with an own background
Answer:
unit NScroll;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms;
type
TMyScrollBox = class(TScrollBox)
private
FNHBitmap: TBitmap;
FNHCanvas: TCanvas;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
procedure SetBitmap(Value: TBitmap);
protected
procedure Painting;
procedure PaintWindow(DC: HDC); override;
published
property BackBitmap: TBitmap read FNHBitmap write SetBitmap;
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
end;
procedure Register;
implementation
constructor TMyScrollBox.Create(Owner: TComponent);
begin
inherited Create(Owner);
FNHBitmap := TBitmap.Create;
FNHCanvas := TControlCanvas.Create;
TControlCanvas(FNHCanvas).Control := Self;
end;
destructor TMyScrollBox.Destroy;
begin
FNHBitmap.Destroy;
FNHCanvas.Destroy;
inherited Destroy;
end;
procedure TMyScrollBox.SetBitmap(Value: TBitmap);
begin
FNHBitmap.Assign(Value);
invalidate;
end;
procedure TMyScrollBox.WMPaint(var Message: TWMPaint);
begin
PaintHandler(Message);
end;
procedure TMyScrollBox.PaintWindow(DC: HDC);
begin
FNHCanvas.Handle := DC;
try
Painting;
finally
FNHCanvas.Handle := 0;
end;
end;
procedure TMyScrollBox.Painting;
var
FDrawHeight, FDrawWidth: Integer;
Row, Column, xl, xt, xw, xh: Integer;
xdl, xdt: Integer;
xRect: TRect;
i: integer;
xhdl: Word;
begin
if (FNHBitmap.width <> 0) and (FNHBitmap.Height <> 0) then
begin
xRect := ClientRect;
FDrawHeight := xRect.Bottom - xRect.Top;
FDrawWidth := xRect.Right - xRect.Left;
xdl := (HorzScrollBar.Position mod FNHBitmap.Width);
xdt := (VertScrollBar.Position mod FNHBitmap.Height);
for Row := 0 to (FDrawHeight div FNHBitmap.Height) + 1 do
begin
for Column := 0 to (FDrawWidth div FNHBitmap.Width) + 1 do
begin
xl := Column * FNHBitmap.Width + xRect.Left - xdl;
xt := Row * FNHBitmap.Height + xRect.Top - xdt;
xw := FNHBitmap.Width;
if (FDrawWidth - xl + xRect.Left) < xw then
xw := (FDrawWidth - xl + xRect.Top);
xh := FNHBitmap.Height;
if (FDrawHeight - xt + xRect.Top) < xh then
xh := (FDrawHeight - xt + xRect.Top);
FNHCanvas.CopyRect(Rect(xl, xt, xl + xw, xt + xh), FNHBitmap.Canvas, Rect(0, 0, xw, xh));
end;
end;
end;
end;
procedure Register;
begin
RegisterComponents('Samples', [TMyScrollBox]);
end;
end.
2007. augusztus 5., vasárnap
How to store TForms and / or their properties in a Paradox blob field
Problem/Question/Abstract:
How to store TForms and / or their properties in a Paradox blob field
Answer:
procedure SaveToField(FField: TBlobField; Form: TComponent);
var
Stream: TBlobStream;
FormName: string;
begin
FormName := Copy(Form.ClassName, 2, 99);
Stream := TBlobStream.Create(FField, bmWrite);
try
Stream.WriteComponentRes(FormName, Form);
finally
Stream.Free;
end;
end;
procedure LoadFromField(FField: TBlobField; Form: TComponent);
var
Stream: TBlobStream;
I: integer;
begin
try
Stream := TBlobStream.Create(FField, bmRead);
try
{delete all components}
for I := Form.ComponentCount - 1 downto 0 do
Form.Components[I].Free;
Stream.ReadComponentRes(Form);
finally
Stream.Free;
end;
except
on EFOpenError do {nothing}
;
end;
end;
2007. augusztus 4., szombat
How to wallpaper the client area of a MDI parent form
Problem/Question/Abstract:
How to wallpaper the client area of a MDI parent form
Answer:
Solve 1:
Here are the basics of how it is done:
type
TForm1 = class(TForm)
Image1: TImage;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FClientInstance,
FPrevClientProc: TFarProc;
procedure ClientWndProc(var Message: TMessage);
public
end;
implementation
procedure TForm1.ClientWndProc(var Message: TMessage);
var
MyDC: hDC;
Ro, Co: Word;
begin
with Message do
case Msg of
WM_ERASEBKGND:
begin
MyDC := TWMEraseBkGnd(Message).DC;
for Ro := 0 to ClientHeight div Image1.Picture.Height do
for Co := 0 to ClientWIDTH div Image1.Picture.Width do
BitBlt(MyDC, Co * Image1.Picture.Width, Ro * Image1.Picture.Height,
Image1.Picture.Width,
Image1.Picture.Height, Image1.Picture.Bitmap.Canvas.Handle, 0, 0,
SRCCOPY);
Result := 1;
end;
else
Result := CallWindowProc(FPrevClientProc, ClientHandle, Msg, wParam, lParam);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
if FileExists(ExtractFilePath(Application.ExeName) + 'backgrnd.bmp') then
begin
Image1.Picture.Bitmap.LoadFromFile(ExtractFilePath(Application.ExeName) +
'backgrnd.bmp');
FClientInstance := MakeObjectInstance(ClientWndProc);
FPrevClientProc := Pointer(GetWindowLong(ClientHandle, GWL_WNDPROC));
SetWindowLong(ClientHandle, GWL_WNDPROC, LongInt(FClientInstance));
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
if (FPrevClientProc <> nil) then
begin
FClientInstance := Pointer(GetWindowLong(ClientHandle, GWL_WNDPROC));
SetWindowLong(ClientHandle, GWL_WNDPROC, Longint(FPrevClientProc));
FreeObjectInstance(FClientInstance);
end;
end;
Solve 2:
You need to do some Windows API level stuff to hook the window proc of MDI client window. This client window occupies the client area of an MDI main from - that's why you can't see the results of your painting.
Here's an example of how you do that. It also illustrates how to create a temporary canvas using a supplied Device Context to facilitate painting the image bitmap. The code looks for the file argyle.bmp in the Windows directory. If you don't have that bitmap, substitute another. Make sure you create an OnDestroy handler and copy the code from FormDestroy here into that handler.
{Example of painting the background of an MDI form}
unit MDIPaint;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs;
type
TForm1 = class(TForm)
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FClientInstance: pointer;
FOldClientProc: pointer;
FBackground: TBitmap;
procedure ClientProc(var Message: TMessage);
public
{ Public declarations }
procedure CreateWnd; override;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.ClientProc(var Message: TMessage);
var
ARect: TRect;
x, y: integer;
SrcRect: TRect;
begin
{if the message is to erase background, tile with the background bitmap}
with Message do
begin
if Msg = WM_ERASEBKGND then
begin
WinProcs.GetClientRect(ClientHandle, ARect);
with TCanvas.Create do
try
Handle := wParam;
SrcRect := Rect(0, 0, FBackground.Width, FBackground.Height);
y := 0;
while y < ARect.Bottom do
begin
x := 0;
while x < ARect.Right do
begin
CopyRect(Bounds(x, y, FBackground.Width, FBackground.Height),
FBackground.Canvas, SrcRect);
inc(x, FBackground.Width);
end;
inc(y, FBackground.Height);
end;
Result := 1;
finally
Handle := 0;
Free;
end;
end
else
{otherwise call the original window proc}
Result := CallWindowProc(FOldClientProc, ClientHandle, Msg, wParam, lParam);
end;
end;
procedure TForm1.CreateWnd;
begin
inherited CreateWnd;
if FormStyle = fsMDIForm then
begin
FBackground := TBitmap.Create;
FBackground.LoadFromFile('c:\windows\argyle.bmp');
FClientInstance := MakeObjectInstance(ClientProc);
FOldClientProc := pointer(SetWindowLong(ClientHandle, GWL_WNDPROC,
longint(FClientInstance)));
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
{reset the original client proc, free the client instance and the bitmap}
SetWindowLong(ClientHandle, GWL_WNDPROC, longint(FOldClientProc));
FreeObjectInstance(FClientInstance);
FBackground.Free;
end;
end.
Solve 3:
Here are the steps to add a wallpaper to the client area of of a MDI parent form:
1. Create a new project
2. Set the form's FormStyle to fsMDIForm
3. Drop an image on the form and select a bitmap into it.
4. Find the { Private Declarations } comment in the form's definition and add these lines right after it:
FClientInstance, FPrevClientProc: TFarProc;
procedure ClientWndProc(var Message: TMessage);
5. Find the "implementation" line and the {$R *.DFM} line that follows it. After that line, enter this code:
procedure TForm1.ClientWndProc(var Message: TMessage);
var
MyDC: hDC;
Ro, Co: Word;
begin
with Message do
case Msg of
WM_ERASEBKGND:
begin
MyDC := TWMEraseBkGnd(Message).DC;
for Ro := 0 to ClientHeight div Image1.Picture.Height do
for Co := 0 to ClientWIDTH div Image1.Picture.Width do
BitBlt(MyDC, Co * Image1.Picture.Width, Ro * Image1.Picture.Height,
Image1.Picture.Width,
Image1.Picture.Height, Image1.Picture.Bitmap.Canvas.Handle, 0, 0,
SRCCOPY);
Result := 1;
end
else
Result := CallWindowProc(FPrevClientProc, ClientHandle, Msg, wParam, lParam);
end;
end;
6. Start an OnCreate method for the form and put these lines in it:
FClientInstance := MakeObjectInstance(ClientWndProc);
FPrevClientProc := Pointer(GetWindowLong(ClientHandle, GWL_WNDPROC));
SetWindowLong(ClientHandle, GWL_WNDPROC, LongInt(FClientInstance));
7. Add a new form to your project and set its FormStyle to fsMDIChild.
Now you have a working MDI project with "wallpaper". The image component is not visible, but its bitmap is replicated to cover the MDI form's client area. There is still one problem; when you minimize the child window its icon will be drawn against a gray rectangle.
2007. augusztus 3., péntek
How to copy text from a TRichEdit to the clipboard with a different font than the original
Problem/Question/Abstract:
I need to ensure that when my TRichEdit copies text to the clipboard, it is copied in a certain font, colour and size. My problem is that my TRichEdit is defaulted to one font and the users are not given the ability to change it. But I want it to pasted into Word (for example) in another font.
Answer:
You can of course compose a rich text file in code and copy that into the clipboard using the standard rich edit clipboard format, but it's a lot of work. A somewhat simpler approach may be to take the rich text as it is in the control (stream to a TMemoryStream, load into a String) and then modify the \fonttbl tag in the file.
procedure TForm1.Button3Click(Sender: TObject);
var
S: string;
ss: TStringstream;
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
richedit1.Lines.SaveToStream(ms);
SetString(S, Pchar(ms.Memory), ms.size);
finally
ms.free
end;
memo1.text := S; {view raw rtf in TMemo to see font table}
S := Stringreplace(S, 'Times New Roman', 'Verdana', []);
ss := TStringstream.Create(S);
try
richedit1.Lines.LoadFromStream(ss);
finally
ss.free
end;
end;
To get the new text into the clipboard proceed as below:
uses
Richedit, Clipbrd;
{$R *.dfm}
procedure CopyStreamToClipboard(fmt: Cardinal; S: TStream);
var
hMem: THandle;
pMem: Pointer;
begin
{Rewind stream position to start}
S.Position := 0;
{Allocate a global memory block the size of the stream data}
hMem := GlobalAlloc(GHND or GMEM_DDESHARE, S.Size);
if hMem <> 0 then
begin
{Succeeded, lock the memory handle to get a pointer to the memory}
pMem := GlobalLock(hMem);
if pMem <> nil then
begin
{Succeeded, now read the stream contents into the memory the pointer points at}
try
S.Read(pMem^, S.Size);
{Rewind stream again, caller may be confused if the stream position is
left at the end}
S.Position := 0;
finally
{Unlock the memory block}
GlobalUnlock(hMem);
end;
{Open clipboard and put the block into it. The way the Delphi clipboard
object is written this will clear the clipboard first.
Make sure the clipboard is closed even in case of an exception. If left open
it would become unusable for other apps.}
Clipboard.Open;
try
Clipboard.SetAsHandle(fmt, hMem);
finally
Clipboard.Close;
end;
end
else
begin
{Could not lock the memory block, so free it again and raise an out of
memory exception}
GlobalFree(hMem);
OutOfMemoryError;
end;
end
else
{Failed to allocate the memory block, raise exception}
OutOfMemoryError;
end;
var
CF_RTF: Word = 0; {set in Initialization section}
procedure TForm1.Button3Click(Sender: TObject);
var
S: string;
ss: TStringstream;
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
richedit1.Lines.SaveToStream(ms);
SetString(S, Pchar(ms.Memory), ms.size);
finally
ms.free
end;
S := Stringreplace(S, 'Times New Roman', 'Verdana', []);
ss := TStringstream.Create(S);
try
// richedit1.Lines.LoadFromStream(ss);
CopyStreamToClipboard(CF_RTF, ss);
finally
ss.free
end;
end;
initialization
CF_RTF := RegisterClipboardFormat(Richedit.CF_RTF);
end.
2007. augusztus 2., csütörtök
Retrieve all directories contained in a path string
Problem/Question/Abstract:
Suppose I have a path string, for example: 'c:\programs\borland\Delphi' , how can I retrieve each single directory name contained in the path (creating a tree of directories)?
Answer:
uses
SysUtils;
procedure GetDirList(const Root: AnsiString; Dirs: TStrings);
var
Found: TSearchRec;
function IsDirectory(F: TSearchRec): Boolean
begin
Result := F.Name <> '.';
Result := Result or (F.Name) <> '..';
Result := Result and (F.Attr and faDirectory = faDirectory);
end;
begin
Dirs.Clear;
if FindFirst(Root + '\*.*', faAnFile, Found) = 0 then
begin
try
if IsDirectory(Found) then
Dirs.Add(Root + '\' + Found.Name);
while FindNext(Found) = 0 do
begin
if IsDirectory(Found) then
Dirs.Add(Root + '\' + Found.Name);
end;
finally
FindFree
end;
end;
end;
2007. augusztus 1., szerda
Number in french plain text
Problem/Question/Abstract:
Converting integer to plain text in French
Answer:
function IntToLetters(N: Integer): string;
function Mille(N: Integer; P: Integer): string;
// Calcul des nombre de 0..99
function Cent(N: Integer): string;
const
X: array[0..20] of string =
('zero', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf',
'dix',
'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept',
'dix-huit', 'dix-neuf', 'vingt');
Y: array[2..10] of string =
('vingt', 'trente', 'quarante', 'cinquante', 'soixante', 'soixante',
'quatre-vingt', 'quatre-vingt', 'cent');
var
A, B: Integer;
R, C: string;
begin
// Si le nombre est inferieur ou egal a 20 on a la solution directe
if (N <= 20) then
begin
R := X[N];
end;
// Si le nombre est superieur a 20
if (N > 20) and (N < 100) then
begin
// on prend la dizaine
A := N div 10;
// on pend l'unit�
B := N mod 10;
// si l'unit� est un, le s�parateur est 'et'
if (B = 1) and (A in [2, 3, 4, 5, 6, 7]) then
C := ' et '
else
C := ' ';
// si l'unite est sup�rieure a 1, le s�parateur est un '-'
if (B > 1) and (A in [2, 3, 4, 5, 6, 7, 8, 9]) then
C := '-';
// si la dizaine est 7 ou 9 on compte les unit�s de 10 ? 19
if (A = 7) or (A = 9) then
B := B + 10;
// On calcule la solution
if (B = 0) then
R := Y[A]
else
R := Y[A] + C + X[B];
end;
Result := R;
end;
// Calcul des nombres de 100..999
var
A, B: Integer;
R: string;
begin
if (N >= 100) then
begin
// on prend la centaine
A := N div 100;
// on prend le reste
B := N mod 100;
if (A = 0) or (A = 1) then
begin
// si la centaine est 0 ou 1
// on calcule et on 'cent' est au singulier
if (B = 0) then
R := 'cent '
else
R := 'cent ' + Cent(B);
end
else
begin
// si la centaine est > 1
if (P = 0) then
begin
// si c'est la fin d'un nombre (P=0)
// on mets 'cents' au pluriel si pas d'unit� sinon on met 'cent' au singulier
if (B = 0) then
R := Cent(A) + ' cents '
else
R := Cent(A) + ' cent ' + Cent(B);
end
else
begin
// si ce n'est pas la fin d'un nombre 'cent' est au singulier
if (B = 0) then
R := Cent(A) + ' cent '
else
R := Cent(A) + ' cent ' + Cent(B);
end;
end;
end
else
begin
// si le nombre est inf�rieur a 100 on le calcule directement
R := Cent(N);
end;
Result := R;
end;
// Function principale
const
Z: array[0..3] of string =
('', 'mille', 'million', 'milliard');
var
B, I: Integer;
R, M: string;
begin
R := '';
I := 0;
// On va d�composer en tranche de 1000 en partant de la droite
while (N > 0) do
begin
// prend une tranche (reste de la division par 1000)
B := N mod 1000;
// le pluriel est utilis� a partir des milliers
if (I = 0) then
M := ' '
else
M := 's ';
if I = 1 then
begin
// on calcule la tranche des milliers
// si le nombre de milliers est sup�rieur a 1 on ecrit le nombre et 'milles'
if (B > 1) then
R := Mille(B, I) + ' ' + Z[I] + M + R;
// sinon on �ecrit 'mille' et pas 'un mille'
if (B = 1) then
R := Z[I] + ' ' + R;
end
else
begin
// on calcule les millions et suivants
// on mets un 's' au pluriel
if (B > 1) then
R := Mille(B, I) + ' ' + Z[I] + M + R;
// on n'en met pas au singulier
if (B = 1) then
R := Mille(B, I) + ' ' + Z[I] + ' ' + R;
end;
// on decale de 3 rangs vers la droite
N := N div 1000;
I := I + 1;
end;
if (R = '') then
R := 'z�ro';
Result := R;
end;
Feliratkozás:
Bejegyzések (Atom)