2004. június 2., szerda
How to switch focus to an existing instance of an application
Problem/Question/Abstract:
How can I switch focus to an existing instance of an application instead of creating a new instance (HPrevInst)?
Answer:
{usual stuff at the top of the project source file}
var
hwnd: Word;
begin
if hPrevInst = 0 then
begin
Application.CreateForm(TForm1, Form1);
Application.Run;
end
else
begin
hwnd := FindWindow('TForm1', nil);
if (not IsWindowVisible(hwnd)) then
begin
ShowWindow(hwnd, sw_ShowNormal);
PostMessage(hwnd, wm_User, 0, 0);
end
else
SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE);
end;
end.
in the form's PAS file add a message response function for the wm_User message.
{in the form declaration}
public
procedure WMUser(var msg: TMessage); message wm_User;
{in the implementation section}
procedure TForm1.WMUser(var msg: TMessage);
begin
Application.Restore;
end;
2004. június 1., kedd
Streaming COM Objects as XML
Problem/Question/Abstract:
Streaming COM Objects as XML
Answer:
Introduction
When I was making my first COM objects I used to think that I could give my COM classes the same shape of regular Delphi ones. I am specifically talking about properties and a "stateful life-style" in which you keep using its methods similarily to what you'd do with a DataSet (i.e. Open, Next, Next, Close). Well yes, COM allows you to do that and if the objects lives on the client's computer everything works fast and efficiently. The problem araises if and when you move your object to another machine. In that situation then your application suddenly starts to slow down and your client becomes dependent on the network condition. Each time you access a property you are invoking a method that executes on another machine. If your code makes such calls continuosly you will be in big trouble. The ideal solution would be to redesign such objects making them "stateless". With "stateless object" I mean those whose methods do all they say they will do (i.e. ExecuteMoneyTransfer) and don't depend on other methods (i.e. ExecuteMoneyTransfer doesn't expect a Commit or Rollback method to be called by the client after it is completion). But often the amount of legacy code makes a resedign not practical. Is it possible then to do anything to improve performance and makes stateful objects stateless? As you would expect it is possible (no point in writing this article otherwise ;-) ). By persisting the object's state in some kind of intermediary format (I choose XML) and streaming it in one shot you can achieve the goal. Remember that this is not an optimal solution and the code I am presenting here is not optimized either. If you are starting from scratch you should design stateless objects.
TlbInf32.dll
Included in Visual Studio 6 and Visual Basic 6.0 CDs you can find a very handy DLL called TlbInf32. You can download the documentation for this file on the MSDN webside. If you don't have Visual Studio you can download the DLL from the website Compiled.org
TlbInf32 includes a set of classes that can help you reading type information for both type libaries and COM objects. Now, download my example by clicking here.
The code
The example is very straightforward. I won't spend too much time on it. There's a simple COM library with an object which implements the following interface:
ISimpleObject = interface(IDispatch)
function Name: WideString[propget, dispid $00000001]; safecall;
procedure Name(Value: WideString)[propput, dispid $00000001]; safecall;
function Age: Integer[propget, dispid $00000002]; safecall;
procedure Age(Value: Integer)[propput, dispid $00000002]; safecall;
end;
Then there's a client application that is able to persist and restore the state of it by using an auxiliary class called TTypeInfoStreamer which is defined as:
TTypeInfoStreamer = class
private
fTLI: _TLIApplication;
public
constructor Create;
function GetObjectAsXML(const anObject: IDispatch): widestring;
procedure SetObjectAsXML(const anObject: IDispatch; aString: widestring);
end;
The two methods GetObjectAsXML and SetObjectAsXMl are what interest us. Please, don't make an example of the code. I put this sample togheter in 10 minutes to answer a question of a guy in a newsgroup. Take a look at the lines I highlighted:
function TTypeInfoStreamer.GetObjectAsXML(const anObject: IDispatch): widestring;
var
xml: DOMDocument30;
intfinfo: InterfaceInfo;
root,
node: IXMLDOMNode;
i: integer;
val: OleVariant;
p: PSafeArray;
begin
p := MakeEmptyParmsArray;
try
intfinfo := fTLI.InterfaceInfoFromObject(anObject);
xml := CoDOMDocument30.Create;
xml.async := FALSE;
root := xml.createNode('element', intfinfo.Get_Name, '');
xml.appendChild(root);
with intfinfo do
for i := 1 to (Members.Count) do
begin
if not (Members[i].InvokeKind = INVOKE_PROPERTYGET) then
Continue;
val := fTLI.InvokeHook(anObject, Members[i].Get_MemberId, INVOKE_PROPERTYGET,
p);
node := xml.createNode('element', Members[i].Name, '');
node.text := VarToStr(val);
root.appendChild(node);
end;
finally
result := root.xml;
SafeArrayDestroy(p);
end;
end;
As you can see we created an instance of the TLIApplication object (included in TlbInf32.dll), passed a pointer to the object we want to stream and then looped tough its Members collections. The members collection is the list of methods implemented by the object. What we want to read is the value of the object's properties so we will only stop on the methods that return the value of a property (Members[i].InvokeKind=INVOKE_PROPERTYGET) . In order to invoke the method we need to call the method TLIApplication.InvokeHook which is defined as:
function InvokeHook(const Object_: IDispatch; ID: OleVariant; InvokeKind: InvokeKinds;
var ReverseArgList: PSafeArray): OleVariant; safecall;
It's interesting to note how the ID parameter could be either the name of the method or its DispID. So, in case you have the DispID already, you wouldn't need to use late bound calls (which first invoke the IDispatch.GetIDOfNames method slowing things down a *lot*). InvokeKind tells the TLIApplication *how* to invoke it and finally the ReverseArgList is a safe array that in our case only contains no values. See the rest of the code to find out how I build one. The result is something like this:
<ISimpleObject>
<Name>Alessandro Federici</Name>
<Age>25</Age>
</ISimpleObject>
Et voila'! We have our COM object persisted into XML! Now we need to set back these values. See the code below.
procedure TTypeInfoStreamer.SetObjectAsXML(const anObject: IDispatch;
aString: widestring);
var
xml: DOMDocument30;
intfinfo: InterfaceInfo;
root,
node: IXMLDOMNode;
i: integer;
val: OleVariant;
p: PSafeArray;
s: string;
begin
p := MakeOneElementArray;
try
intfinfo := fTLI.InterfaceInfoFromObject(anObject);
xml := CoDOMDocument30.Create;
xml.async := FALSE;
xml.loadXML(aString);
root := xml.documentElement;
with root do
for i := 0 to (childNodes.length - 1) do
begin
s := childNodes[i].nodeName;
SetOneElementArray(p, childNodes[i].Text);
fTLI.InvokeHook(anObject, s, INVOKE_PROPERTYPUT, p);
end;
finally
SafeArrayDestroy(p);
end;
end;
As you can see we did the exact opposite of what the had done before except that in this case we invoked the method as a property writer. I hope this will demistify a little how to read COM type information and stream its contents in an arbitraty format. The TTypeInfoStreamer class is far from being a complete class but feel free to use the code as a start. Happy coding!
2004. május 31., hétfő
Select or find a TTreeView node by caption
Problem/Question/Abstract:
How to select or find a TTreeView node by caption
Answer:
Solve 1:
function GetNodeByCaption(NodeCaption: string): TTreeNode;
var
X: Integer;
begin
Result := nil;
for X := 0 to TreeView1.Items.Count - 1 do
begin
if (TreeView1.Items[X].Caption = NodeCaption) then
Result := TreeView1.Items[X];
Break;
end;
end;
Solve 2:
Returns a node based on the text property. Set AVisible to show the new node:
function GetNodeByText(ATree: TTreeView; AValue: string;
AVisible: Boolean): TTreeNode;
var
Node: TTreeNode;
begin
Result := nil;
if ATree.Count = 0 then
Exit;
Node := ATree.Items[0];
while Node <> nil do
begin
if UpperCase(Node.Text) = AValue then
begin
Result := Node;
if AVisible then
Result.MakeVisible;
Break;
end;
Node := Node.GetNext;
end;
end;
2004. május 30., vasárnap
How to copy a 2D array with picture greylevels to an image (2)
Problem/Question/Abstract:
I have been developing a program to display and manipulate medical images which consist of 2D arrays of greyscale values as described. As was observed, the Pixels property is way too slow. Here's what I discovered. I think you'll find it a big improvement.
Answer:
Assuming your data is stored in an array of bytes named TestArray, for example:
TestArray: array[0..127, 0..127] of byte { ... }
ArrayPtr := addr(TestArray); {ArrayPtr: pointer}
In this case we are going to display on the bitmap of a TImage component that has been dropped on the canvas and named Image1.
Image1.Picture.Bitmap.Width := 128;
Image1.Picture.Bitmap.Height := 128;
This is a Windows API function that will copy the bits in TestArray, pointed to by ArrayPtr, into an HBitmap structure, in this case Image1.Picture.Bitmap.Handle.
SetBitmapBits(Image1.Picture.Bitmap.Handle, sizeof(TestArray), ArrayPtr);
Image1.Refresh; {must refresh before changes are displayed}
You still have to deal with the palette, but this technique works great for me.
2004. május 29., szombat
How to set the DisplayFormat of a TDateTime field to time only at runtime
Problem/Question/Abstract:
I'm running a simple query that returns a variable amount of columns somtimes with a DateTime column. How can I set at runtime the Displayformat property or any other way to format the column as a time only field. In other words, I can't seem to find where to set the DisplayFormat property at runtime.
Answer:
Here's one way:
procedure FormatDateFieldsAsTime(DS: TDataSet; TimeFormat: string);
var
f: integer;
begin
for f := 0 to DS.FieldCount - 1 do
if DS.Fields[f] is TDateTimeField then
TDateTimeField(DS.Fields[f]).DisplayFormat := TimeFormat;
end;
Apply this to the query after it's been run, like:
FormatDateFieldsAsTime(Query1, 'hh:mm:ss');
The DisplayFormat is available (assuming you're not creating any persistant fields for this dynamic query) from the query's (or other TDataSet's) Fields property.
2004. május 28., péntek
How to specify a line break in a TRichEdit
Problem/Question/Abstract:
I need to be able to (preferrably dynamically as the user is typing text) to specify a line break of say 70 characters so that the cursor will go to a new line upon reaching the 70 character limit. Actually it would be best to break on the last word boundary but even a break at 70 characters would give me a start.
Answer:
I've had a play with this and the following is the best I could come up with quickly. At least it may give you a start:
Set a Variable called Backpace : Boolean = False ;
procedure GetCurrentRC(re1: TRichedit; var row, col: LongInt);
begin
{Get Current Row and Column Values for Richedit Control}
with re1 do
begin
Row := sendMessage(handle, EM_LINEFROMCHAR, Selstart, 0);
Col := selstart - sendmessage(handle, EM_LINEINDEX, row, 0);
end;
end;
procedure TForm1.re1SelectionChange(Sender: TObject);
var
RTRow, RTCol: LongInt;
begin
GetCurrentRC(re1, RTRow, RTCol);
if (rtCol = 70) and (not Backspace) then
re1.Lines[rtRow] := Memo1.Lines[rtRow] + #13#10;
end;
procedure TForm1.Re1KeyPress(Sender: TObject; var Key: Char);
begin
{If Backspacing we don't want it to jump down again}
if key = #8 then
backspace := True
else
backspace := False;
end;
I think that's about right. You would have to search on the position of any space if you wanted to break on a word boundary.
2004. május 27., csütörtök
How to paint an arc on a TCanvas
Problem/Question/Abstract:
How to paint an arc on a TCanvas
Answer:
procedure PlotArc(const Canvas: TCanvas; const Center: TPoint; const Radius: Integer;
const StartAngle: Single; const StopAngle: Single);
function GetPositionForAngle(const Angle: Single): TPoint;
var
CosAngle: Extended;
SinAngle: Extended;
begin
SinCos(DegToRad(Angle), SinAngle, CosAngle);
Result.X := Round(Center.X + Radius * SinAngle);
Result.Y := Round(Center.Y - Radius * CosAngle);
end;
var
Index: Integer;
begin
with GetPositionForAngle(StartAngle) do
Canvas.MoveTo(X, Y);
for Index := Ceil(StartAngle) to Floor(StopAngle) do
with GetPositionForAngle(Index) do
Canvas.LineTo(X, Y);
with GetPositionForAngle(StopAngle) do
Canvas.LineTo(X, Y);
end;
2004. május 26., szerda
Save a TImagelist with all its images to a file
Problem/Question/Abstract:
How to save a TImagelist with all its images to a file
Answer:
There are ready-made methods for saving any component including all its children to a file. For writing components use WriteComponentResFile(path + source filename , component name source)
WriteComponentResFile('C:\imagelist1.bin', imagelist1);
For reading the data back to a component: component := ReadComponentResFile(path + source filename , component name traget)
imagelist1 := ReadComponentResFile('c:\imagelist1.bin', nil) as TImagelist;
Tip 1 - Reading the component will give the same name of the component written so don't try to load it to another component, even if it was the same type. You will get a duplicate name and delphi will crash. But you can jump over this as a programmer
Tip 2 - Get benfit of storing the heavy components inside compressed files, so you can get smaller programs
2004. május 25., kedd
Floating toolbar
Problem/Question/Abstract:
Floating toolbar
Answer:
All you have to do is handle Windows' wm_NCHitTest message.
(Compare to the tip how to drag a window without a caption bar. It's the same technique.)
unit Dragmain;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
procedure WMNCHitTest(var M: TWMNCHitTest); message wm_NCHitTest;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.WMNCHitTest(var M: TWMNCHitTest);
begin
inherited; { call the inherited message handler }
if M.Result = htClient then { is the click in the client area? }
M.Result := htCaption; { if so, make Windows think it's }
{ on the caption bar. }
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Close;
end;
end.
2004. május 24., hétfő
IDE harddisk serial number (Part 2)
Problem/Question/Abstract:
In my previous article I described the way to extract s/n through call DeviceIoControl with DFP_RECEIVE_DRIVE_DATA control code. But on NT it works only under account with administrative priveleges. Now I've found the way to do this under 'everyone' account.
Answer:
Warning! On Win9x smartvsd.vxd must be installed: simply copy it from
\windows\system\ to \windows\system\iosubsys\ and reboot.
// (c) Alex Konshin mailto:akonshin@earthlink.net 30 jul 2000
program IdeSN;
// PURPOSE: Simple console application that extract first IDE disk serial number.
{$APPTYPE CONSOLE}
uses
Windows,
SysUtils; // only for Win32Platform and SysErrorMessage
//-------------------------------------------------------------
function GetIdeDiskSerialNumber: string;
type
TSrbIoControl = packed record
HeaderLength: ULONG;
Signature: array[0..7] of Char;
Timeout: ULONG;
ControlCode: ULONG;
ReturnCode: ULONG;
Length: ULONG;
end;
SRB_IO_CONTROL = TSrbIoControl;
PSrbIoControl = ^TSrbIoControl;
TIDERegs = packed record
bFeaturesReg: Byte; // Used for specifying SMART "commands".
bSectorCountReg: Byte; // IDE sector count register
bSectorNumberReg: Byte; // IDE sector number register
bCylLowReg: Byte; // IDE low order cylinder value
bCylHighReg: Byte; // IDE high order cylinder value
bDriveHeadReg: Byte; // IDE drive/head register
bCommandReg: Byte; // Actual IDE command.
bReserved: Byte; // reserved. Must be zero.
end;
IDEREGS = TIDERegs;
PIDERegs = ^TIDERegs;
TSendCmdInParams = packed record
cBufferSize: DWORD;
irDriveRegs: TIDERegs;
bDriveNumber: Byte;
bReserved: array[0..2] of Byte;
dwReserved: array[0..3] of DWORD;
bBuffer: array[0..0] of Byte;
end;
SENDCMDINPARAMS = TSendCmdInParams;
PSendCmdInParams = ^TSendCmdInParams;
TIdSector = packed record
wGenConfig: Word;
wNumCyls: Word;
wReserved: Word;
wNumHeads: Word;
wBytesPerTrack: Word;
wBytesPerSector: Word;
wSectorsPerTrack: Word;
wVendorUnique: array[0..2] of Word;
sSerialNumber: array[0..19] of Char;
wBufferType: Word;
wBufferSize: Word;
wECCSize: Word;
sFirmwareRev: array[0..7] of Char;
sModelNumber: array[0..39] of Char;
wMoreVendorUnique: Word;
wDoubleWordIO: Word;
wCapabilities: Word;
wReserved1: Word;
wPIOTiming: Word;
wDMATiming: Word;
wBS: Word;
wNumCurrentCyls: Word;
wNumCurrentHeads: Word;
wNumCurrentSectorsPerTrack: Word;
ulCurrentSectorCapacity: ULONG;
wMultSectorStuff: Word;
ulTotalAddressableSectors: ULONG;
wSingleWordDMA: Word;
wMultiWordDMA: Word;
bReserved: array[0..127] of Byte;
end;
PIdSector = ^TIdSector;
const
IDE_ID_FUNCTION = $EC;
IDENTIFY_BUFFER_SIZE = 512;
DFP_RECEIVE_DRIVE_DATA = $0007C088;
IOCTL_SCSI_MINIPORT = $0004D008;
IOCTL_SCSI_MINIPORT_IDENTIFY = $001B0501;
DataSize = sizeof(TSendCmdInParams) - 1 + IDENTIFY_BUFFER_SIZE;
BufferSize = SizeOf(SRB_IO_CONTROL) + DataSize;
W9xBufferSize = IDENTIFY_BUFFER_SIZE + 16;
var
hDevice: THandle;
cbBytesReturned: DWORD;
pInData: PSendCmdInParams;
pOutData: Pointer; // PSendCmdOutParams
Buffer: array[0..BufferSize - 1] of Byte;
srbControl: TSrbIoControl absolute Buffer;
procedure ChangeByteOrder(var Data; Size: Integer);
var
ptr: PChar;
i: Integer;
c: Char;
begin
ptr := @Data;
for i := 0 to (Size shr 1) - 1 do
begin
c := ptr^;
ptr^ := (ptr + 1)^;
(ptr + 1)^ := c;
Inc(ptr, 2);
end;
end;
begin
Result := '';
FillChar(Buffer, BufferSize, #0);
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin // Windows NT, Windows 2000
// Get SCSI port handle
hDevice := CreateFile(
'\\.\Scsi0:', // Note: '\\.\C:' requires administrative permissions.
GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil, OPEN_EXISTING, 0, 0);
if hDevice = INVALID_HANDLE_VALUE then
Exit;
try
srbControl.HeaderLength := SizeOf(SRB_IO_CONTROL);
System.Move('SCSIDISK', srbControl.Signature, 8);
srbControl.Timeout := 2;
srbControl.Length := DataSize;
srbControl.ControlCode := IOCTL_SCSI_MINIPORT_IDENTIFY;
pInData := PSendCmdInParams(PChar(@Buffer)
+ SizeOf(SRB_IO_CONTROL));
pOutData := pInData;
with pInData^ do
begin
cBufferSize := IDENTIFY_BUFFER_SIZE;
bDriveNumber := 0;
with irDriveRegs do
begin
bFeaturesReg := 0;
bSectorCountReg := 1;
bSectorNumberReg := 1;
bCylLowReg := 0;
bCylHighReg := 0;
bDriveHeadReg := $A0;
bCommandReg := IDE_ID_FUNCTION;
end;
end;
if not DeviceIoControl(hDevice, IOCTL_SCSI_MINIPORT,
@Buffer, BufferSize, @Buffer, BufferSize,
cbBytesReturned, nil) then
Exit;
finally
CloseHandle(hDevice);
end;
end
else
begin // Windows 95 OSR2, Windows 98
hDevice := CreateFile('\\.\SMARTVSD', 0, 0, nil,
CREATE_NEW, 0, 0);
if hDevice = INVALID_HANDLE_VALUE then
Exit;
try
pInData := PSendCmdInParams(@Buffer);
pOutData := @pInData^.bBuffer;
with pInData^ do
begin
cBufferSize := IDENTIFY_BUFFER_SIZE;
bDriveNumber := 0;
with irDriveRegs do
begin
bFeaturesReg := 0;
bSectorCountReg := 1;
bSectorNumberReg := 1;
bCylLowReg := 0;
bCylHighReg := 0;
bDriveHeadReg := $A0;
bCommandReg := IDE_ID_FUNCTION;
end;
end;
if not DeviceIoControl(hDevice, DFP_RECEIVE_DRIVE_DATA,
pInData, SizeOf(TSendCmdInParams) - 1, pOutData,
W9xBufferSize, cbBytesReturned, nil) then
Exit;
finally
CloseHandle(hDevice);
end;
end;
with PIdSector(PChar(pOutData) + 16)^ do
begin
ChangeByteOrder(sSerialNumber, SizeOf(sSerialNumber));
SetString(Result, sSerialNumber, SizeOf(sSerialNumber));
end;
end;
//=============================================================
var
s: string;
rc: DWORD;
begin
s := GetIdeDiskSerialNumber;
if s = '' then
begin
rc := GetLastError;
if rc = 0 then
WriteLn('IDE drive is not support SMART feature')
else
WriteLn(SysErrorMessage(rc));
end
else
WriteLn('Disk serial number: ''', s, '''');
end.
See also IdeInfo2 on my homepage: http://home.earhlink.net/~akonshin/
Component Download: http://home.earthlink.net/~akonshin/files/IdeSN.zip
2004. május 23., vasárnap
Getting the icon of an application, library or document
Problem/Question/Abstract:
How can I get the icon of an application or the icons in a DLL?
Answer:
ExtractAssociatedIcon
To get the icon of an application or document we can use this API function (declared in the ShellAPI unit):
function ExtractAssociatedIcon(hInst: HINST; lpIconPath: PChar;
var lpiIcon: Word): HICON; stdcall;
hInst: The application handle. This value is contained in the predefined variable HInstance.
lpIconPath: A pointer to a character buffer that should contain a null terminated string with the full path name of the application, library (DLL) or document. If it is a document, the function will place there the full pathname of the associated application from where the icon was extracted, so we should allocate a buffer large enough.
lpiIcon: The icon index (the first icon in the file has an index of 0). If lpIconPath specifies a document, then lpiIcon is set by the function (that's why it is passed by reference) to the index position of the actual icon taken from the associated executable (defined in the file association).
Return value:
If the function fails, it returns 0. If it succeeds, it returns an icon handle, which is an integer value Windows uses to identify the allocated resource. It is not necessary to call the API DestroyIcon to release the icon since it'll be deallocated automatically when the application finishes, although you can do it if you want.
Sample call
Now, what do we do with the icon handle? Normally what we want is an icon, namely and instance of the TIcon class. All we have to do is create a TIcon object and assign this handle to its Handle property. If later we assign the Handle property to another value, the previous icon will be automatically be released. The same happens if the TIcon object is freed. Here is an example that changes the icon of the form:
procedure TForm1.Button1Click(Sender: TObject);
var
IconIndex: word;
Buffer: array[0..2048] of char;
IconHandle: HIcon;
begin
StrCopy(@Buffer, 'C:\Windows\Help\Windows.hlp');
IconIndex := 0;
IconHandle := ExtractAssociatedIcon(HInstance, Buffer, IconIndex);
if IconHandle <> 0 then
Icon.Handle := IconHandle;
end;
GetAssociatedIcon
Unfortunately, ExtractAssociatedIcon fails if the file does not exists on disk, so we defined a procedure that gets the icon of a file whether it exists or not, and can also get the small icon (ideal for a TListView that can be shown in vsIcon or vsReport view styles). The procedure receives three parameters: the filename and two pointers to HICON (integer) variables: one for the large icon (32x32) and another one for the small icon (16x16). Any of them can be nil if you don't need one of these icons. The icons "returned" by the procedure must be freed with the DestroyIcon API. This will be done automatically if you assign the icon handle (HICON) to the Handle property of a TIcon object
(the icon will be released when this object gets freed or a new value is assigned to it).
uses
Registry, ShellAPI;
type
PHICON = ^HICON;
procedure GetAssociatedIcon(FileName: TFilename;
PLargeIcon, PSmallIcon: PHICON);
// Gets the icons of a given file
var
IconIndex: word; // Position of the icon in the file
FileExt, FileType: string;
Reg: TRegistry;
p: integer;
p1, p2: pchar;
label
noassoc;
begin
IconIndex := 0;
// Get the extension of the file
FileExt := UpperCase(ExtractFileExt(FileName));
if ((FileExt <> '.EXE') and (FileExt <> '.ICO')) or
not FileExists(FileName) then
begin
// If the file is an EXE or ICO and it exists, then
// we will extract the icon from this file. Otherwise
// here we will try to find the associated icon in the
// Windows Registry...
Reg := nil;
try
Reg := TRegistry.Create(KEY_QUERY_VALUE);
Reg.RootKey := HKEY_CLASSES_ROOT;
if FileExt = '.EXE' then
FileExt := '.COM';
if Reg.OpenKeyReadOnly(FileExt) then
try
FileType := Reg.ReadString('');
finally
Reg.CloseKey;
end;
if (FileType <> '') and Reg.OpenKeyReadOnly(
FileType + '\DefaultIcon') then
try
FileName := Reg.ReadString('');
finally
Reg.CloseKey;
end;
finally
Reg.Free;
end;
// If we couldn't find the association, we will
// try to get the default icons
if FileName = '' then
goto noassoc;
// Get the filename and icon index from the
// association (of form '"filaname",index')
p1 := PChar(FileName);
p2 := StrRScan(p1, ',');
if p2 <> nil then
begin
p := p2 - p1 + 1; // Position of the comma
IconIndex := StrToInt(Copy(FileName, p + 1,
Length(FileName) - p));
SetLength(FileName, p - 1);
end;
end;
// Attempt to get the icon
if ExtractIconEx(pchar(FileName), IconIndex,
PLargeIcon^, PSmallIcon^, 1) <> 1 then
begin
noassoc:
// The operation failed or the file had no associated
// icon. Try to get the default icons from SHELL32.DLL
try // to get the location of SHELL32.DLL
FileName := IncludeTrailingBackslash(GetSystemDir)
+ 'SHELL32.DLL';
except
FileName := 'C:\WINDOWS\SYSTEM\SHELL32.DLL';
end;
// Determine the default icon for the file extension
if (FileExt = '.DOC') then
IconIndex := 1
else if (FileExt = '.EXE')
or (FileExt = '.COM') then
IconIndex := 2
else if (FileExt = '.HLP') then
IconIndex := 23
else if (FileExt = '.INI')
or (FileExt = '.INF') then
IconIndex := 63
else if (FileExt = '.TXT') then
IconIndex := 64
else if (FileExt = '.BAT') then
IconIndex := 65
else if (FileExt = '.DLL')
or (FileExt = '.SYS')
or (FileExt = '.VBX')
or (FileExt = '.OCX')
or (FileExt = '.VXD') then
IconIndex := 66
else if (FileExt = '.FON') then
IconIndex := 67
else if (FileExt = '.TTF') then
IconIndex := 68
else if (FileExt = '.FOT') then
IconIndex := 69
else
IconIndex := 0;
// Attempt to get the icon.
if ExtractIconEx(pchar(FileName), IconIndex,
PLargeIcon^, PSmallIcon^, 1) <> 1 then
begin
// Failed to get the icon. Just "return" zeroes.
if PLargeIcon <> nil then
PLargeIcon^ := 0;
if PSmallIcon <> nil then
PSmallIcon^ := 0;
end;
end;
end;
Sample call
This example will change the icon of your form:
procedure TForm1.Button1Click(Sender: TObject);
var
SmallIcon: HICON;
begin
GetAssociatedIcon('file.doc', nil, @SmallIcon);
if SmallIcon <> 0 then
Icon.Handle := SmallIcon;
end;
Copyright (c) 2001 Ernesto De Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php
2004. május 22., szombat
Delphi translation of the IAutoComplete interface
Problem/Question/Abstract:
I'm looking for a Delphi translation of the IAutoComplete interface in Microsofts shldisp.h. Can anyone point me in the right direction, please?
Answer:
Here is the translation and a TEdit decendant I wrote a while back:
unit uAutoComplete;
interface
uses
Windows, SysUtils, Controls, Classes, ActiveX, ComObj, stdctrls, Forms, Messages;
const
IID_IAutoComplete: TGUID = '{00bb2762-6a77-11d0-a535-00c04fd7d062}';
IID_IAutoComplete2: TGUID = '{EAC04BC0-3791-11d2-BB95-0060977B464C}';
CLSID_IAutoComplete: TGUID = '{00BB2763-6A77-11D0-A535-00C04FD7D062}';
IID_IACList: TGUID = '{77A130B0-94FD-11D0-A544-00C04FD7d062}';
IID_IACList2: TGUID = '{470141a0-5186-11d2-bbb6-0060977b464c}';
CLSID_ACLHistory: TGUID = '{00BB2764-6A77-11D0-A535-00C04FD7D062}';
CLSID_ACListISF: TGUID = '{03C036F1-A186-11D0-824A-00AA005B4383}';
CLSID_ACLMRU: TGUID = '{6756a641-de71-11d0-831b-00aa005b4383}';
type
IACList = interface(IUnknown)
['{77A130B0-94FD-11D0-A544-00C04FD7d062}']
function Expand(pszExpand: POLESTR): HResult; stdcall;
end;
const
{Options for IACList2}
ACLO_NONE = 0; {don't enumerate anything}
ACLO_CURRENTDIR = 1; {enumerate current directory}
ACLO_MYCOMPUTER = 2; {enumerate MyComputer}
ACLO_DESKTOP = 4; {enumerate Desktop Folder}
ACLO_FAVORITES = 8; {enumerate Favorites Folder}
ACLO_FILESYSONLY = 16; {enumerate only the file system}
type
IACList2 = interface(IACList)
['{470141a0-5186-11d2-bbb6-0060977b464c}']
function SetOptions(dwFlag: DWORD): HResult; stdcall;
function GetOptions(var pdwFlag: DWORD): HResult; stdcall;
end;
IAutoComplete = interface(IUnknown)
['{00bb2762-6a77-11d0-a535-00c04fd7d062}']
function Init(hwndEdit: HWND; const punkACL: IUnknown; pwszRegKeyPath,
pwszQuickComplete: POLESTR): HResult; stdcall;
function Enable(fEnable: BOOL): HResult; stdcall;
end;
const
{Options for IAutoComplete2}
ACO_NONE = 0;
ACO_AUTOSUGGEST = $1;
ACO_AUTOAPPEND = $2;
ACO_SEARCH = $4;
ACO_FILTERPREFIXES = $8;
ACO_USETAB = $10;
ACO_UPDOWNKEYDROPSLIST = $20;
ACO_RTLREADING = $40;
type
IAutoComplete2 = interface(IAutoComplete)
['{EAC04BC0-3791-11d2-BB95-0060977B464C}']
function SetOptions(dwFlag: DWORD): HResult; stdcall;
function GetOptions(out pdwFlag: DWORD): HResult; stdcall;
end;
TEnumString = class(TInterfacedObject, IEnumString)
private
FStrings: TStringList;
FCurrIndex: integer;
public
{IEnumString}
function Next(celt: Longint; out elt; pceltFetched: PLongint): HResult; stdcall;
function Skip(celt: Longint): HResult; stdcall;
function Reset: HResult; stdcall;
function Clone(out enm: IEnumString): HResult; stdcall;
{VCL}
constructor Create;
destructor Destroy; override;
end;
TACOption = (acAutoAppend, acAutoSuggest, acUseArrowKey);
TACOptions = set of TACOption;
TACSource = (acsList, acsHistory, acsMRU, acsShell);
TACEdit = class(TEdit)
private
FACList: TEnumString;
FAutoComplete: IAutoComplete;
FACEnabled: boolean;
FACOptions: TACOptions;
FACSource: TACSource;
function GetACStrings: TStringList;
procedure SetACEnabled(const Value: boolean);
procedure SetACOptions(const Value: TACOptions);
procedure SetACSource(const Value: TACSource);
protected
procedure CreateWnd; override;
procedure DestroyWnd; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property ACStrings: TStringList read GetACStrings;
property ACEnabled: boolean read FACEnabled write SetACEnabled;
property ACOptions: TACOptions read FACOptions write SetACOptions;
property ACSource: TACSource read FACSource write SetACSource;
end;
implementation
{ IUnknownInt }
function TEnumString.Clone(out enm: IEnumString): HResult;
begin
Result := E_NOTIMPL;
pointer(enm) := nil;
end;
constructor TEnumString.Create;
begin
inherited Create;
FStrings := TStringList.Create;
FCurrIndex := 0;
end;
destructor TEnumString.Destroy;
begin
FStrings.Free;
inherited;
end;
function TEnumString.Next(celt: Integer; out elt; pceltFetched: PLongint): HResult;
var
I: Integer;
wStr: WideString;
begin
I := 0;
while (I < celt) and (FCurrIndex < FStrings.Count) do
begin
wStr := FStrings[FCurrIndex];
TPointerList(elt)[I] := CoTaskMemAlloc(2 * (Length(wStr) + 1));
StringToWideChar(wStr, TPointerList(elt)[I], 2 * (Length(wStr) + 1));
Inc(I);
Inc(FCurrIndex);
end;
if pceltFetched <> nil then
pceltFetched^ := I;
if I = celt then
Result := S_OK
else
Result := S_FALSE;
end;
function TEnumString.Reset: HResult;
begin
FCurrIndex := 0;
Result := S_OK;
end;
function TEnumString.Skip(celt: Integer): HResult;
begin
if (FCurrIndex + celt) <= FStrings.Count then
begin
Inc(FCurrIndex, celt);
Result := S_OK;
end
else
begin
FCurrIndex := FStrings.Count;
Result := S_FALSE;
end;
end;
{ TACEdit }
constructor TACEdit.Create(AOwner: TComponent);
begin
inherited;
FACList := TEnumString.Create;
FACEnabled := true;
FACOptions := [acAutoAppend, acAutoSuggest, acUseArrowKey];
end;
procedure TACEdit.CreateWnd;
var
Dummy: IUnknown;
Strings: IEnumString;
begin
inherited;
if HandleAllocated then
begin
try
Dummy := CreateComObject(CLSID_IAutoComplete);
if (Dummy <> nil) and (Dummy.QueryInterface(IID_IAutoComplete, FAutoComplete) =
S_OK) then
begin
case FACSource of
acsHistory:
Strings := CreateComObject(CLSID_ACLHistory) as IEnumString;
acsMRU:
Strings := CreateComObject(CLSID_ACLMRU) as IEnumString;
acsShell:
Strings := CreateComObject(CLSID_ACListISF) as IEnumString;
else
Strings := FACList as IEnumString;
end;
if S_OK = FAutoComplete.Init(Handle, Strings, nil, nil) then
begin
SetACEnabled(FACEnabled);
SetACOptions(FACOptions);
end;
end;
except
{CLSID_IAutoComplete is not available}
end;
end;
end;
destructor TACEdit.Destroy;
begin
FACList := nil;
inherited;
end;
procedure TACEdit.DestroyWnd;
begin
if (FAutoComplete <> nil) then
begin
FAutoComplete.Enable(false);
FAutoComplete := nil;
end;
inherited;
end;
function TACEdit.GetACStrings: TStringList;
begin
Result := FACList.FStrings;
end;
procedure TACEdit.SetACEnabled(const Value: boolean);
begin
if (FAutoComplete <> nil) then
begin
FAutoComplete.Enable(FACEnabled);
end;
FACEnabled := Value;
end;
procedure TACEdit.SetACOptions(const Value: TACOptions);
const
Options: array[TACOption] of integer = (ACO_AUTOAPPEND, ACO_AUTOSUGGEST,
ACO_UPDOWNKEYDROPSLIST);
var
Option: TACOption;
Opt: DWORD;
AC2: IAutoComplete2;
begin
if (FAutoComplete <> nil) then
begin
if S_OK = FAutoComplete.QueryInterface(IID_IAutoComplete2, AC2) then
begin
Opt := ACO_NONE;
for Option := Low(Options) to High(Options) do
begin
if (Option in FACOptions) then
Opt := Opt or DWORD(Options[Option]);
end;
AC2.SetOptions(Opt);
end;
end;
FACOptions := Value;
end;
procedure TACEdit.SetACSource(const Value: TACSource);
begin
if FACSource <> Value then
begin
FACSource := Value;
RecreateWnd;
end;
end;
initialization
finalization
end.
2004. május 21., péntek
Getting rid of the initial flash of a WS_MAXIMIZE child
Problem/Question/Abstract:
How can I open an MDI child form so that it's initially in a maximized state? Every time I try, it appears in its normal size, then maximizes visibly. I can't hide it because Delphi won't let me, and if I trick it by hiding it in CreateParams, it's maximized for a split second (just after OnShow()), then is reduced to normal size, then is re-maximized. This is all happening somewhere after OnShow() and I can't seem to stop it ... I just need it to open already maximized, and all ready to go. ... Help!
Answer:
One thing you might have noticed is that child forms set with the wsMaximized property have a visible flash when they're first created. First they're created in a normal state, then they maximize. This is more annoying than problematic.
For those of you who are experienced in mucking about with form properties, you might think that setting the form's window style to WS_MAXIMIZE in the CreateParams method would do the trick. Alas, that doesn't work either. But don't worry, there's a very simple solution.
One of the ways you can prevent the user from seeing background operations on a window is to prevent it from painting, then having it refresh after the changes have been made. To the user, it will appear as if the screen was automagically changed in the blink of an eye. With respect to opening up a maximized MDI child form in an MDI application, this is exactly the type of thing we're going to do.
The specific function that allows us to prevent screen painting is a WinAPI function called LockWindowUpdate. LockWindowUpdate takes a single parameter &mdash the handle of the window &mdash and prevents it from painting until LockWindowUpdate is called again with a parameter of '0.' So, with respect to our particular problem, to prevent a maximized MDI child from flashing at create, you enclose its create statement between two LockWindowUpdate calls like so:
LockWindowUpdate(MyMDIMainForm.Handle);
MyMDIChild := TMyMDIChild.Create(Application);
LockWindowUpdate(0);
Pretty simple, huh? Notice that I locked the screen painting with respect to the MDI form, not the MDI child. That's important, because if you tried to lock the update for the child, you'd get an error because the handle is invalid. In any case, use this technique for all your MDI applications to avoid the initial flash.
2004. május 20., csütörtök
How to display hints always under the mouse cursor
Problem/Question/Abstract:
How to display hints always under the mouse cursor
Answer:
This code snippet shows how to make your popup hint windows behave more like normal windows apps. Instead of always being square under the control they belong to, they are based on where the mouse is. This uses the GetIconInfo API, which is only available for Win32.
Add the following to your main form's OnCreate event handler:
procedure TMainForm.FormCreate(Sender: TObject);
begin
Application.OnShowHint := GetHintInfo;
end;
Add the following declaration to your main form's protected declartion:
procedure GetHintInfo(var HintStr: string; var CanShow: boolean; var HintInfo: THintInfo);
And, finally, add this procedure to your main form:
procedure TMainForm.GetHintInfo(var HintStr: string; var CanShow: boolean; var HintInfo: THintInfo);
var
II: TIconInfo;
Bmp: Windows.TBitmap;
begin
with HintInfo do
begin
{Make sure we have a control that fired the hint}
if HintControl = nil then
exit;
{Convert the cursor's coordinates from relative to hint to relative to screen}
HintPos := HintControl.ClientToScreen(CursorPos);
{Get some information about the cursor that is used for the hint control}
GetIconInfo(Screen.Cursors[HintControl.Cursor], II);
{Get some information about the bitmap representing the cursor}
GetObject(II.hbmMask, SizeOf(Windows.TBitmap), @Bmp);
{If the info did not include a color bitmap then the mask bitmap is really two bitmaps, an AND & XOR mask. Increment our Y position by the bitmap's height}
if II.hbmColor = 0 then
inc(HintPos.Y, Bmp.bmHeight div 2)
else
inc(HintPos.Y, Bmp.bmHeight);
{Subtract out the Y hotspot position}
dec(HintPos.Y, II.yHotSpot);
{We are responsible for cleaning up the bitmap handles returned by GetIconInfo}
DeleteObject(II.hbmMask);
DeleteObject(II.hbmColor);
end;
end;
Feliratkozás:
Bejegyzések (Atom)