2007. július 31., kedd
Save and load a TTreeView to / from a stream
Problem/Question/Abstract:
I'd like to use the TreeView component for hierarchizing some data. For this, I need to add to every node an integer property which will refer to the primary key field of an associated database. Alas, I fear that the TreeView "SaveToFile" and "LoadFromFile" methods save/ load only the Text property! Then, how can I save and load this integer property (and by the way, the imageindex) for every node?
Answer:
By writing your own save and load routines. Untested! Don't forget to rewind the stream before loading when you test this code.
procedure SaveTreeviewToStream(tv: TTreeview; S: TStream);
var
writer: TWriter;
node: TTreeNode;
begin
Assert(Assigned(tv));
Assert(Assigned(S));
writer := TWriter.Create(S, 4096);
try
node := tv.Items[0];
writer.WriteListBegin;
while node <> nil do
begin
writer.WriteInteger(node.level);
writer.WriteString(node.Text);
writer.WriteInteger(node.Imageindex);
writer.WriteInteger(Integer(node.data));
node := node.GetNext;
end;
writer.WriteListEnd;
writer.FlushBuffer;
finally
writer.Free;
end;
end;
procedure LoadTreeviewFromStream(tv: TTreeview; S: TStream);
var
reader: TReader;
node: TTreeNode;
level: Integer;
begin
Assert(Assigned(tv));
Assert(Assigned(S));
tv.Items.BeginUpdate;
try
tv.Items.Clear;
reader := TReader.Create(S, 4096);
try
node := nil;
reader.ReadListBegin;
while not Reader.EndOfList do
begin
level := reader.ReadInteger;
if node = nil then
{create root node, ignore its level}
node := tv.Items.Add(nil, '')
else
begin
if level = node.level then
node := tv.Items.Add(node, '')
else if level > node.level then
node := tv.Items.AddChild(node, '')
else
begin
while Assigned(node) and (level < node.level) do
node := node.Parent;
node := tv.Items.Add(node, '');
end;
end;
node.Text := Reader.ReadString;
node.ImageIndex := Reader.ReadInteger;
node.Data := Pointer(Reader.ReadInteger);
end;
reader.ReadListEnd;
finally
reader.Free;
end;
finally
tv.items.Endupdate;
end;
end;
I'd rather suggest to use the data pointer as a pointer to a real object, not as integer (in the SaveTreeviewToStream procedure). You could add more complex info inside this object, like type information, or even the data objects itself. Type information is essential if your treeview browses through different tables of your database.
2007. július 30., hétfő
Count the number of Mondays between two given dates
Problem/Question/Abstract:
How to count the number of Mondays between two given dates
Answer:
Solve 1:
function NumMondays(dt1, dt2: TDateTime): integer;
var
Date1, Date2, DateSpan: integer;
Weekday1, DaysInStub: integer;
MondayInStub: Boolean;
begin
{Make sure date 1 is smaller than date 2}
Date1 := MinIntValue([Trunc(dt1), Trunc(dt2)]);
Date2 := MaxIntValue([Trunc(dt1), Trunc(dt2)]);
{First approximation: complete weeks}
DateSpan := Date2 - Date1 + 1;
result := DateSpan div 7;
{Now check if there's a Monday in the stub}
MondayInStub := false;
DaysInStub := DateSpan mod 7;
Weekday1 := DayOfWeek(Date1);
case Weekday1 of
{Sunday}
1: MondayInStub := DaysInStub > 0;
{Monday}
2: MondayInStub := true; {Starts and ends with Monday}
{Sunday}
3..7: MondayInStub := (Weekday1 + DaysInStub > 9 {2+7});
end;
if MondayInStub then
inc(result);
end;
Solve 2:
Something like this should do the trick. I included the variable setup and display of results from my little test so that it will be obvious what I did.
procedure TForm1.Button1Click(Sender: TObject);
var
cnt: integer;
StartDate, EndDate: TDate;
begin
cnt := 0;
StartDate := StrToDate('4/21/2003');
EndDate := StrToDate('5/30/2003');
{Actual Monday counting}
repeat
if DayOfWeek(StartDate) = 2 then {2 = Monday (Sun = 1 .. Sat = 7) }
inc(cnt);
StartDate := StartDate + 1;
until
StartDate = EndDate;
label1.Caption := IntToStr(cnt);
end;
2007. július 29., vasárnap
How to test for resource depletion
Problem/Question/Abstract:
I have a process that, under some conditions, can deplete a machine's resources. Is there a way for my application to check how close it is to that point?
Answer:
unit Sysresources;
interface
uses
Windows, Sysutils;
const
GFSR_SYSTEMRESOURCES = 0;
GFSR_GDIRESOURCES = 1;
GFSR_USERRESOURCES = 2;
function GetSystemResources(typ: Word): Integer;
implementation
var
hDll: HMODULE;
pProc: function(typ: word): Integer stdcall;
function GetSystemResources(typ: word): Integer;
begin
result := pProc(typ);
end;
function InternalGetSystemresources(typ: Word): Integer; stdcall;
begin
result := -1;
end;
initialization
pProc := InternalGetSystemresources;
if Win32Platform <> VER_PLATFORM_WIN32_NT then
begin
hdll := LoadLibrary('rsrc32.dll');
if hdll <> 0 then
begin
@pProc := getProcAddress(hdll, '_MyGetFreeSystemResources32@4');
if @pProc = nil then
pProc := InternalGetSystemresources;
end;
end;
finalization
if hDLL <> 0 then
FreeLibrary(hdll);
end.
2007. július 28., szombat
Right-align a menu item (2)
Problem/Question/Abstract:
I want to write a TMenu component where all items and sub menus are right justified.
Answer:
You can change the item's justification, if you add the MFT_RIGHTJUSTIFY constant to the item's type (fType member of the TMenuItemInfo structure). You can do it in the main menu's OnChange event handler. Here's an example:
procedure TForm1.MainMenu1Change(Sender: TObject; Source: TMenuItem; Rebuild:
Boolean);
var
XHandle: HMENU;
XMenuItemInfo: TMenuItemInfo;
XBuffer: array[0..79] of Char;
begin
XHandle := TMainMenu(Sender).Handle;
XMenuItemInfo.cbSize := 44;
XMenuItemInfo.fMask := MIIM_TYPE;
XMenuItemInfo.dwTypeData := XBuffer;
XMenuItemInfo.cch := SizeOf(XBuffer);
if GetMenuItemInfo(XHandle, 0, true, XMenuItemInfo) then
begin
XMenuItemInfo.fType := XMenuItemInfo.fType or MFT_RIGHTORDER or MFT_RIGHTJUSTIFY;
XMenuItemInfo.fMask := MIIM_TYPE;
SetMenuItemInfo(XHandle, 0, true, XMenuItemInfo);
end;
end;
2007. július 27., péntek
Attach a TComboBox to the column of a TStringGrid
Problem/Question/Abstract:
How to attach a TComboBox to the column of a TStringGrid
Answer:
Solve 1:
Here is one way to do it, using a single combobox that moves from cell to cell as required.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
Grids;
type
TForm1 = class(TForm)
StringGrid1: TStringGrid;
ComboBox1: TComboBox;
procedure ComboBox1Exit(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer; var
CanSelect: Boolean);
private
{ Private declarations }
procedure CMDialogKey(var msg: TCMDialogKey); message CM_DIALOGKEY;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.CMDialogKey(var msg: TCMDialogKey);
begin
if Activecontrol = ComboBox1 then
begin
if msg.CharCode = VK_TAB then
begin
{set focus back to the grid and pass the tab key to it}
stringgrid1.setfocus;
stringgrid1.perform(WM_KEYDOWN, msg.charcode, msg.keydata);
{swallow this message}
msg.result := 1;
Exit;
end;
end;
inherited;
end;
procedure TForm1.ComboBox1Exit(Sender: TObject);
begin
with sender as TComboBox do
begin
hide;
if itemindex >= 0 then
with stringgrid1 do
cells[col, row] := items[itemindex];
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ComboBox1.visible := false;
end;
procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
var
R: TRect;
org: TPoint;
begin
with Sender as TStringGrid do
if (ACol = 2) and (ARow >= FixedRows) then
begin
{entered the column associated to the combobox}
{get grid out of selection mode}
perform(WM_CANCELMODE, 0, 0);
{position the control on top of the cell}
R := CellRect(Acol, Arow);
org := Self.ScreenToClient(ClientToScreen(R.topleft));
with ComboBox1 do
begin
setbounds(org.X, org.Y, r.right - r.left, height);
itemindex := Items.IndexOf(Cells[acol, arow]);
Show;
BringTofront;
{focus the combobox and drop down the list}
SetFocus;
DroppedDown := true;
end;
end;
end;
end.
Solve 2:
unit GridCombo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, StdCtrls;
type
TFrmGridCombo = class(TForm)
StringGrid1: TStringGrid;
BtnSave: TButton;
StringGrid2: TStringGrid;
BtnLoad: TButton;
procedure StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer; var
CanSelect: Boolean);
private
FCBox: TComboBox;
procedure ComboClick(Sender: TObject);
public
{ Public declarations }
end;
var
FrmGridCombo: TFrmGridCombo;
implementation
{$R *.DFM}
procedure TFrmGridCombo.StringGrid1SelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
var
thisRect: TRect; {Notational clarity.}
begin
if (ARow = 1) and (ACol <> 0) then
begin
if Assigned(FCBox) then
FCBox.Free;
FCBox := TComboBox.Create(self);
FCBox.Parent := self;
thisRect := StringGrid1.CellRect(ACol, ARow);
FCBox.Left := thisRect.Left + StringGrid1.Left + 2;
FCBox.Top := thisRect.Top + StringGrid1.Top + 2;
FCBox.Width := (thisRect.Right - thisRect.Left);
FCBox.Height := (thisRect.Bottom - thisRect.Top);
FCBox.Items.LoadFromFile('File2.Txt');
FCBox.SetFocus;
FCBox.OnClick := ComboClick;
end
else if Assigned(FCBox) then
begin
FCBox.Free;
FCBox := nil;
end;
end;
procedure TFrmGridCombo.ComboClick(Sender: TObject);
begin
if Sender is TComboBox then
StringGrid1.Cells[StringGrid1.Col, StringGrid1.Row] := TComboBox(Sender).Text;
end;
end.
2007. július 26., csütörtök
How to convert an integer value to a Roman Numeral representation
Problem/Question/Abstract:
How to convert an integer value to a Roman Numeral representation
Answer:
Converts an integer value to a string containing a roman numeric code ("XVII"):
{Parameters: - Num: Integer to convert.
Return Value: - Roman numerical representation of the passed integer value.
History: 12/7/99 "Philippe Ranger" (PhilippeRanger@compuserve.com)}
function IntToRoman(num: Cardinal): string; {returns num in capital roman digits}
const
Nvals = 13;
vals: array[1..Nvals] of word = (1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900,
1000);
roms: array[1..Nvals] of string[2] = ('I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC',
'C', 'CD', 'D', 'CM', 'M');
var
b: 1..Nvals;
begin
result := '';
b := Nvals;
while num > 0 do
begin
while vals[b] > num do
dec(b);
dec(num, vals[b]);
result := result + roms[b]
end;
end;
2007. július 25., szerda
How to keep your application focused at all times
Problem/Question/Abstract:
I want my application to keep focus at any time. So, if someone clicks another window, I want my application to retrieve back focus.
Answer:
Solve 1:
To get your application into the foreground in W98, ME, W2K and XP, instead of using SetForegroundWindow, try this:
procedure ShowMe;
var
Th1, Th2: Cardinal;
begin
Th1 := GetCurrentThreadId;
Th2 := GetWindowThreadProcessId(GetForegroundWindow, nil);
AttachThreadInput(Th2, Th1, true);
try
SetForegroundWindow(Application.Handle);
finally
AttachThreadInput(Th2, Th1, false);
end;
end;
Solve 2:
As well as the SetForegroundWindow (if you are using Win9X and not WinNT/2000), you could trick the system that your application is a running screensaver. In this case it will not loose focus, for screensavers by design maintain focus.
{ ... }
var
old: Bool;
begin
{Make it a Screensaver}
SystemParametersInfo(SPI_SCREENSAVERRUNNING, Word(True), @old, 0);
or
{Make it not a Screensaver}
SystemParametersInfo(SPI_SCREENSAVERRUNNING, Word(False), @old, 0);
2007. július 24., kedd
MS-SQL : connection is in use by another statement
Problem/Question/Abstract:
MS-SQL : connection is in use by another statement
Answer:
When porting a larger database application (130k LOC) that worked fine with Oracle and InterBase to MS-SQL (6.5), I frequently got the error message 'connection is in use by another statement'.
At first, creating a new TDatabase for each TTable/ TQuery seemed to be necessary.
Then I found what was 'wrong' (not really wrong.. :-)
To speed up some of my queries, I had set the property Unidirectional to true. Delphi creates for such queries only one cursor (versus two for bidirectional queries or TTables). After removing the assignments of Unidirectional := true the error message disappeared and everything worked fine.
The following code resulted in the exception 'connection is in use by another statement':
// dataBaseNameS : string is the name of the alias (MS-SQL 6.5)
begin
Query1 := TQuery.Create(Application);
with Query1 do
begin
DatabaseName := dataBaseNameS;
SQL.Text := 'SELECT * FROM ABLESTOP';
// the exception disappears if the following is removed
Unidirectional := True;
Open;
end;
ShowMessage('ok')
Table1 := TTable.Create(Self);
with Table1 do
begin
DatabaseName := dataBaseNameS;
TableName := 'COMPONENT_PLAN';
UpdateMode := upWhereKeyOnly;
Open
end;
Table1.Insert;
Table1.FieldByName('PARTNO').AsString := IntToStr(GetTickCount);
Table1.FieldByName('ID').AsString := 'WWxx';
Table1.FieldByName('VERSION').AsInteger := 1;
// the exception will occurr in the next statement:
// "Connection is in use by another statement"
Table1.Post;
end;
2007. július 23., hétfő
Play Musical Notes via PC Speaker Class
Problem/Question/Abstract:
Play Musical Notes via PC Speaker Class
Answer:
This is a simple class that plays a formatted musical string. It is reminiscent of the old GWBASIC days whereby one could play a string of notes via the PC speaker. I know that WAV and MIDI files are available in todays technology, but sometimes one does not need all that overhead. The class is useful for certain types of alarms (specially if the user has his sound card volume muted) or simple "Cell Phone" like jingles. The trick of the matter in Delphi is that the standard DELPHI implementation of BEEP takes no arguments and has only one sound. However the WIN API BEEP() takes two arguments.
ie.
BOOL Beep(
DWORD dwFreq, // sound frequency, in hertz
DWORD dwDuration // sound duration, in milliseconds
);
Parameters
dwFreq
Windows NT:
Specifies the frequency, in hertz, of the sound. This parameter must be in the range 37 through 32,767 (0x25 through 0x7FFF).
Windows 95:
The parameter is ignored.
dwDuration
Windows NT:
Specifies the duration, in milliseconds, of the sound.
Windows 95:
The parameter is ignored.
As can be seen it appears that BEEP() is NOT supported on WIN95, but is OK from there upwards. (I have not tested it on WIN95, but assume you will just get a monotone ???? - anyone for comment)
It is easily called by prefixing the unit
ie. Windows.Beep(Freq,Duration)
The format of the "Music String" is a comma delimited (",<" terminated) string in the following formats. (The string is CASE-INSENSITIVE and [] means optional with defaults).
A..G[+ or -][0..5][/BEATS] and
@[/BEATS]
Where A..G is the Note to be played.
+ or - is optional Sharp or Flat designator respectively. (default is normal NULL)
0..5 is optional Octave range (default = 1)
/BEATS is number of 100ms to hold the note (default = 1)
where @ is a musical pause
/BEATS is the number of beats to pause for (default = 1)
where ,< is the END OF STRING terminator.
Properties:
DefaultOctave : Used if no 0..5 designator specified in format. (System Default = 1)
BetweenNotesPause : Use to set number MS gap between notes (faster or slower default = 100ms)
Simple Example:
procedure TForm1.Button3Click(Sender: TObject);
var
Organ: TMusicPlayer;
begin
Organ := TMusicPlayer.Create;
Organ.Play('A,C,C+,D/3,C,A,C,A,@,F,D/4,<');
Organ.Play('A,A3/2,G4,G/3,@/2,D-0/4,<');
Organ.Free;
end;
Any enhancements or additional ideas welcome. Happy jingeling.
unit Music;
interface
uses Windows, SysUtils;
// ===========================================================================
// Mike Heydon May 2002
// Simple Music Player Class Win98/2000 (Win95 not supported)
// Implements Notes A,A#/Bb,C,C#/Db,D,D#,Eb,E,F,F#/Gb,G,G#/Ab
// Caters for Octaves 0..5
// In Between Note Pause setable.
// Defailt Octave setable.
//
// Based on Frequency Matrix
//
// Octave0 Octave1 Octave2 Octave3 Octave4 Octave5
// A 55.000 110.000 220.000 440.000 880.000 1760.000
// A#/Bb 58.270 116.541 233.082 466.164 932.328 1864.655
// B 61.735 123.471 246.942 493.883 987.767 1975.533
// C 65.406 130.813 261.626 523.251 1046.502 2093.005
// C#/Db 69.296 138.591 277.183 554.365 1108.731 2217.461
// D 73.416 146.832 293.665 587.330 1174.659 2349.318
// D#/Eb 77.782 155.563 311.127 622.254 1244.508 2489.016
// E 82.407 164.814 329.628 659.255 1318.510 2637.020
// F 87.307 174.614 349.228 698.456 1396.913 2793.826
// F#/Gb 92.499 184.997 369.994 739.989 1479.978 2959.955
// G 97.999 195.998 391.995 783.991 1567.982 3135.963
// G#/Ab 103.826 207.652 415.305 830.609 1661.219 3322.438
//
// @ = Pause
// < = End of Music String Marker
//
// ===========================================================================
type
TOctaveNumber = 0..5;
TNoteNumber = -1..11;
TMusicPlayer = class(TObject)
private
Octave,
FDefaultOctave: TOctaveNumber;
NoteIdx: TNoteNumber;
FBetweenNotesPause,
Duration: integer;
protected
function ParseNextNote(var MS: string): boolean;
public
constructor Create;
procedure Play(const MusicString: string);
property DefaultOctave: TOctaveNumber read FDefaultOctave
write FDefaultOctave;
property BetweenNotesPause: integer read FBetweenNotesPause
write FBetweenNotesPause;
end;
// ---------------------------------------------------------------------------
implementation
const
MAXSTRING = 2048; // ASCIIZ String max length
MHERTZ: array[0..11, 0..5] of integer = // Array of Note MHertz
((55, 110, 220, 440, 880, 1760), // A
(58, 117, 233, 466, 932, 1865), // A+ B-
(62, 123, 247, 494, 988, 1976), // B
(65, 131, 262, 523, 1047, 2093), // C
(69, 139, 277, 554, 1109, 2217), // C+ D-
(73, 147, 294, 587, 1175, 2349), // D
(78, 156, 311, 622, 1245, 2489), // D+ E-
(82, 165, 330, 659, 1319, 2637), // E
(87, 1745, 349, 698, 1397, 2794), // F
(92, 185, 370, 740, 1480, 2960), // F+ G-
(98, 196, 392, 784, 1568, 3136), // G
(105, 208, 415, 831, 1661, 3322) // G+ A-
);
// =======================================
// Create the object and set defaults
// =======================================
constructor TMusicPlayer.Create;
begin
FDefaultOctave := 1;
FBetweenNotesPause := 100;
end;
// ===========================================================
// Parse the next note and set Octave,NoteIdx and Duration
// ===========================================================
function TMusicPlayer.ParseNextNote(var MS: string): boolean;
var
NS: string; // Note String
Beats,
CommaPos: integer;
Retvar: boolean;
begin
Retvar := false; // Assume Error Condition
Beats := 1;
Duration := 0;
NoteIdx := 0;
Octave := FDefaultOctave;
CommaPos := pos(',', MS);
if (CommaPos > 0) then
begin
NS := trim(copy(MS, 1, CommaPos - 1)); // Next Note info
MS := copy(MS, CommaPos + 1, MAXSTRING); // Remove note from music string
if (length(NS) >= 1) and (NS[1] in ['@'..'G']) then
begin
Retvar := true; // Valid Note - set return type true
// Resolve NoteIdx
NoteIdx := byte(NS[1]) - 65; // Map 'A'..'G' into 0..11 or -1
NS := copy(NS, 2, MAXSTRING); // Remove the Main Note ID
// Handle the @ Pause first
if NoteIdx = -1 then
begin
if (length(NS) >= 1) and (NS[1] = '/') then
Beats := StrToIntDef(copy(NS, 2, MAXSTRING), 1);
Sleep(100 * Beats);
Retvar := false; // Nothing to play
NS := ''; // Stop further processing
end;
// Resolve Sharp or Flast
if (length(NS) >= 1) and (NS[1] in ['+', '-']) then
begin
if NS[1] = '+' then // # Sharp
inc(NoteIdx)
else if NS[1] = '-' then // b Flat
dec(NoteIdx);
if NoteIdx = -1 then
NoteIdx := 11; // Roll A Flat to G Sharp
NS := copy(NS, 2, MAXSTRING); // Remove Flat/Sharp ID
end;
// Resolve Octave Number - Default := FDefaultOctave
if (length(NS) >= 1) and (NS[1] in ['0'..'5']) then
begin
Octave := byte(NS[1]) - 48; // map '0'..'5' to 0..5 decimal
NS := copy(NS, 2, MAXSTRING); // Remove Octave Number
end;
// Resolve Number of Beats - Default = 1
if (length(NS) >= 1) and (NS[1] = '/') then
Beats := StrToIntDef(copy(NS, 2, MAXSTRING), 1);
Duration := 100 * Beats;
end;
end
else
MS := ''; // Signal end of music string
Result := Retvar;
end;
// ===================================
// Play the passed music string
// ===================================
procedure TMusicPlayer.Play(const MusicString: string);
var
MS: string; // Music String
begin
MS := trim(UpperCase(MusicString));
while (MS <> '') do
begin
if ParseNextNote(MS) then
begin
Windows.Beep(MHERTZ[NoteIdx, Octave], Duration);
Sleep(FBetweenNotesPause);
end;
end;
end;
end.
2007. július 22., vasárnap
How to display hints on the status bar
Problem/Question/Abstract:
How to display hints on the status bar
Answer:
The following unit demonstrates displaying the hint on the status bar:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls;
type
TForm1 = class(TForm)
StatusBar1: TStatusBar;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure ApplicationHint(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.ApplicationHint(Sender: TObject);
begin
StatusBar1.Panels[0].Text := GetLongHint(Application.Hint);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnHint := ApplicationHint;
end;
end.
2007. július 21., szombat
How to disable copying to clipboard from a TRichEdit
Problem/Question/Abstract:
I have been trying all day to keep a descendant of TRichEdit from copying/ cutting to the clipboard with the use of the [ctrl] +[c] and [ctrl] + [x] keyboard shortcuts with no luck at all.
Answer:
Try a different approach: to copy something there has to be a selection, otherwise there is nothing to copy. So attach a handler to the controls OnSelectionChange event. This handler contains the line:
with Sender as TRichEdit do
SelLength := 0;
2007. július 20., péntek
How to load a main menu into a TTreeView
Problem/Question/Abstract:
How to load a main menu into a TTreeView
Answer:
procedure AddToTree(Menu: TMenuItem; Tree: TTreeView; PNode: TTreeNode);
var
x: Integer;
Node: TTreeNode;
begin
Node := Tree.Items.AddChild(PNode, Menu.Caption);
if Menu.Count > 0 then
begin
for x := 0 to Menu.Count - 1 do
begin
AddToTree(Menu.Items[x], Tree, Node);
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
x: Integer;
begin
TreeView1.Items.Clear;
for x := 0 to MainMenu1.Items.Count - 1 do
begin
AddToTree(MainMenu1.Items[x], TreeView1, nil);
end;
end;
2007. július 19., csütörtök
Delphi code window doesn't receive focus on hitting breakpoints
Problem/Question/Abstract:
We have one computer at work running Delphi 4 on Win98.
When we attempt to debug our D4 exe on this machine by setting breakpoints, the D4 code window becomes the topmost window, but DOES NOT receive focus!
Answer:
Check that your WIN.INI file contains the following:
[Compatibility95]
DELPHI32=0x00000002
2007. július 18., szerda
How to create an icon from a TBitmap
Problem/Question/Abstract:
How to create an icon from a TBitmap
Answer:
You must create two bitmaps, a mask bitmap (called the "AND" bitmap) and a image bitmap (called the XOR bitmap). You can pass the handles to the "AND" and "XOR" bitmaps to the Windows API function CreateIconIndirect() and use the returned icon handle in your application:
procedure TForm1.Button1Click(Sender: TObject);
var
IconSizeX: Integer;
IconSizeY: Integer;
AndMask: TBitmap;
XOrMask: TBitmap;
IconInfo: TIconInfo;
Icon: TIcon;
begin
{Getting the icon size}
IconSizeX := GetSystemMetrics(SM_CXICON);
IconSizeY := GetSystemMetrics(SM_CYICON);
{Creating the "And" mask}
AndMask := TBitmap.Create;
AndMask.Monochrome := true;
AndMask.Width := IconSizeX;
AndMask.Height := IconSizeY;
{Drawing on the "And" mask}
AndMask.Canvas.Brush.Color := clWhite;
AndMask.Canvas.FillRect(Rect(0, 0, IconSizeX, IconSizeY));
AndMask.Canvas.Brush.Color := clBlack;
AndMask.Canvas.Ellipse(4, 4, IconSizeX - 4, IconSizeY - 4);
{Test drawing}
Form1.Canvas.Draw(IconSizeX * 2, IconSizeY, AndMask);
{Creating the "XOR" mask}
XOrMask := TBitmap.Create;
XOrMask.Width := IconSizeX;
XOrMask.Height := IconSizeY;
{Drawing onto the "XOR" mask}
XOrMask.Canvas.Brush.Color := ClBlack;
XOrMask.Canvas.FillRect(Rect(0, 0, IconSizeX, IconSizeY));
XOrMask.Canvas.Pen.Color := clRed;
XOrMask.Canvas.Brush.Color := clRed;
XOrMask.Canvas.Ellipse(4, 4, IconSizeX - 4, IconSizeY - 4);
{Test drawing}
Form1.Canvas.Draw(IconSizeX * 4, IconSizeY, XOrMask);
{Create an icon}
Icon := TIcon.Create;
IconInfo.fIcon := true;
IconInfo.xHotspot := 0;
IconInfo.yHotspot := 0;
IconInfo.hbmMask := AndMask.Handle;
IconInfo.hbmColor := XOrMask.Handle;
Icon.Handle := CreateIconIndirect(IconInfo);
{Destroying temporary bitmaps}
AndMask.Free;
XOrMask.Free;
{Test drawing}
Form1.Canvas.Draw(IconSizeX * 6, IconSizeY, Icon);
{Assigning the application's icon}
Application.Icon := Icon;
{Forcing a repaint}
InvalidateRect(Application.Handle, nil, true);
{Free the icon}
Icon.Free;
end;
Feliratkozás:
Bejegyzések (Atom)