Thursday, December 25, 2008

Delphi 2009

Installed Delphi 2009 a week ago and have been trying to update my code. The big change is Unicode support. All strings are now Unicode strings by default so there are a lot of instances that need reassigning to AnsiString. That was not too difficult.

My next attempt was to use 32 bit images in an ImageList. Not as easy as expected. I tried to load PNG images but the transparency did not come out very well. There was a faint grey border around the images, as if the semi-transparent pixels were grey instead of semi-transparent (fully transparent pixels were OK). After many hours of experimenting I found out that 32 bit bitmaps work perfectly. So now I use Inkscape to draw the icons, export to a PNG file, then use Pixelformer to convert from PNG to 32 bit BMP (using A8R8G8B8 format), then load the BMPs into the TImageList (which is set to 32 bits) and assign clNone as the transparent color. Pixelformer is a nice painting program that handles transparency very well and is perfect for this job.

The alpha-channel images can be used on TButtons as well. Unfortunately, they do not work on TSpeedButtons. So I thought of changing all TSpeedButtons to TButtons, but TButtons do not have a Down state. I searched the web and found out I could use the BN_SETSTATE message to make a button seem depressed. The problem is, the button does not stay depressed: as soon as you move the focus away, the button pops up again. This strange phenomenon was partly explained by Dennis Martin in this web page. It seems that a Click event is fired when the button looses focus. Dennis has a solution, but I wanted to create a component to emulate a TSpeedButton. I came up with a different way. Here is the code (feel free to use and share):

//TdhStickyButton, stays down when Down is true.
//intercepts Kill_Focus message to set a flag that shows
// that it is down and was just killed (lost focus).
//intercepts WM_Command, which receives a Click message,
// and only sends it along if it was not just killed in a down state.
// also, resets temporary flag and sets the Down state appropriately
// (otherwise it reverts automatically).
type
TdhStickyButton = class(TButton)
private
FDDown: Boolean;
FJustKilledWhenDown: Boolean;
procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
procedure CNCommand(var Message: TWMCommand); message CN_COMMAND;
procedure SetDownState(Value: Boolean);
protected
public
constructor Create(AOwner: TComponent); override;
published
property Down: Boolean read FDDown write SetDownState default false;
end;

procedure Register;

implementation

procedure Register;
begin
RegisterComponents('Additional', [TdhStickyButton]);
end;

constructor TdhStickyButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDDown := false;
end;

procedure TdhStickyButton.WMKillFocus(var Message: TWMKillFocus);
begin
if FDDown then FJustKilledWhenDown := true else FJustKilledWhenDown := false;
inherited;
end;

procedure TdhStickyButton.CNCommand(var Message: TWMCommand);
begin
if (Message.NotifyCode = BN_CLICKED) and not(FJustKilledWhenDown) then Click;
SendMessage(self.Handle, BM_SETSTATE, Longint(FDDown), 0);
FJustKilledWhenDown := false;
end;

procedure TdhStickyButton.SetDownState(Value: Boolean);
begin
FDDown := Value;
SendMessage(self.Handle, BM_SETSTATE, Longint(FDDown), 0);
end;

A StickyButton is used like a regular button. If you want to show it down, just set its 'Down' property to true. The button will not toggle between down and up automatically, you have to do it with code. Also, if you attach an Action to the button, it will not toggle together with the Action's 'checked' property, as SpeedButtons do; again, you have to do it with code.

Thursday, April 24, 2008

How to Set the Language in a PowerPoint presentation

To change the language of all text in all slides (including the Notes of the slides), use the following macro:

Sub SetLangUK()
'set language to UK for all slides and notes:
Dim scount, j, k, fcount
scount = ActivePresentation.Slides.Count
For j = 1 To scount
fcount = ActivePresentation.Slides(j).Shapes.Count
For k = 1 To fcount 'change all shapes:
If ActivePresentation.Slides(j).Shapes(k).HasTextFrame Then
ActivePresentation.Slides(j).Shapes(k).TextFrame _
.TextRange.LanguageID = msoLanguageIDEnglishUK
End If
Next k
'change notes:
fcount = ActivePresentation.Slides(j).NotesPage.Shapes.Count
For k = 1 To fcount 'change all shapes:
If ActivePresentation.Slides(j).NotesPage.Shapes(k).HasTextFrame Then
ActivePresentation.Slides(j).NotesPage.Shapes(k).TextFrame _
.TextRange.LanguageID = msoLanguageIDEnglishUK
End If
Next k
Next j
End Sub

I got half of this code from Antonín Otáhal and added the part about the NotesPage.

Sunday, June 24, 2007

Upgrading to Delphi 2007 Update 1

Why should seemingly simple things induce so much frustration? I attempted to update my Delphi 2007 and lost more than 5 hours in the process and I haven’t finished yet. The InstallAware wizard is still installing. Everything started normally when I received a notification that Update 1 was available. So I downloaded the setup program and started the process. It seems that the setup program first uninstalls the whole of Delphi 2007 and then installs the updated copy. However, after uninstalling, it displayed a message saying that “Extraction of installation data downloaded from the web has failed. What would you like to do? Download a fresh copy of the installation data. Try to extract the existing download data again”. None of the options had any effect (I tried both many times) so the only choice was to quit the installer, leaving me with a computer without Delphi on it anymore! After googling a bit, I logged into Borland and downloaded the ‘Full download zip file (757MB)’ from CodeGear. However, installing from this file also seemed to produce exactly the same strange behaviour. Even though downloading from the web seemed to work fine, ‘extraction of data’ failed and nothing worked. I found the solution by luck: when the message appears, first select ‘Download a fresh copy’, then quit the installer and restart it. The installer will now properly extract the previously received file, but may fail on a subsequent one. Do the same thing for each file. This may require that you restart the installer many times, but eventually things work out OK.

Saturday, May 12, 2007

Vista troubles

As anyone with even a tiny experience in upgrading from one OS to another would expect, going from Windows XP to Vista is not a trivial task. I installed Vista on one computer so that I could use it as a test-bed for upgrading my software ‘Viewbox’. Installation went fine except for the very frustrating fact that Vista Home Premium cannot be installed as an upgrade to XP Professional. You will need Vista Business or Ultimate to do that. So a clean install was done, requiring re-installation of a large number of software afterwards.
Then came the task of making Viewbox run on Vista (I already knew that Viewbox aborted on loading). I installed Delphi 2007 Professional and recompiled but the problem still persisted, flagging the error: ‘the computer does not have HTML Help support’. I knew this was not possible, because HTML Help support is built into Internet Explorer and depends on ‘hhctrl.ocx’, which is installed with Vista. The problem was that Viewbox could not find the ocx file. After a bit of googling, I found out that the file has changed location. If you want to find it, you should not rely on the registry entry, but you should look into the Windows folder. See the web page of The Helpware Group for more info.
However, even after solving this problem, Viewbox would not load. The problem was that I was using a TImageList component with a width of zero. Apparently, Windows XP has no problems with that, but Vista cannot tolerate it and shuts down the offending software. Fixing this was easy. Of course, you may ask why I was using a TImageList of zero width. That is another story.
After these changes, Viewbox seems to be running just fine under Vista. However, new security measures have been implemented in Vista. They include the User Account Control (UAC) system (for a detailed explanation, try this doc from Microsoft: WindowsVistaUACDevReqs.doc). The UAC does not allow writing of files in the C:\Program Files folder. This is a problem, because Viewbox saves its various settings in the Program Files\Viewbox folder as an INI file. I am not going to explain the details of the UAC (read the doc mentioned above). What you should know if you are programming in Delphi 2007, is that the XPManifest now includes an entry for the security level, as follows:
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel
level="asInvoker"
uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
Setting ‘level’ equal to ‘asInvoker’ tells Vista not to implement virtualizing, so if your software tries to write to C:\Program Files\ it will fail. I have not figured out how to make Delphi change the Manifest contents so that virtualizing of files is possible.

Tuesday, February 27, 2007

TListBox bug

Another one of those bugs that make our life difficult. I have been trying to make a list box with variable item height. I wanted the height of each item to vary, depending on the item, so I thought I would associate a dummy object with each string of the list box, using code like this:

MyListBox.AddItem(aStr, Pointer(theHeight));

Then I would use an OnMeasureItem event to set the height:

procedure MyForm.MyListBoxMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer);
begin
Height := integer(MyListBox.Items.Objects[Index]);
end;

However, this does not work. The reason is rather interesting. When the AddItem procedure is called, the string is first added to the list box, then Delphi triggers the OnMeasureItem event, BEFORE the object has been added, so the event finds no object in the Items.Objects collection.
My workaround was to add the height as the first character of the string:

MyListBox.Items.Add(Char(theHeight) + aStr);

Then, in the OnMeasureItem procedure, I strip the character and convert it to an integer value:

Height := byte(MyListBox.Items[Index][1]);

Note that this will only work if the variable stored in the first character of the string is not zero, otherwise it will be mistaken as a string termination character and a null string will be added to the list box.

Wednesday, September 27, 2006

One year with the Prius

One year has passed since I got my Toyota Prius. I have been keeping a record of kilometres travelled and gas consumed. The average consumption over approximately 13000 Km has been about 5 lt/100 km. I have an Excel file here, which contains a graph of ‘lt/100 km’. During the past year I have tried to let the tank empty as much as possible and then fill it up with 20 Euros. However, sometimes this was not possible, so you will see some spikes in the graph; these are artefacts of the recording procedure. The true average consumption is calculated as the total amount of litres over the whole year divided by the number of kilometres travelled.
Overall, I am still very pleased with this car. The only problem is limited visibility, especially towards the back.

Tuesday, August 29, 2006

TListView troubles

I have been trying to write some owner-draw procedures for a TListView in Delphi. Specifically, I need to draw some small bitmaps in the vsReport style. I thought this would be easy. So I used the OnCustomDrawSubItem event and all seemed fine until I started changing the width of the columns during run-time. The problem was that ‘column.width’ was not being updated during the dragging and the result was a mess. After looking into the source code of the ComCtrls unit I decided to write a custom control that would update the column widths properly. Again, I thought this would be easy. I spent almost all day trying to figure out why things were not working. Finally I discovered this blog entry: http://thomasfreudenberg.com/blog/comments/352.aspx.
It seems that Microsoft has changed the notification for TListView and HDN_TRACK may not work. So, if you are having the same problems, here is my complete solution. It emulates a OnColumnTrack event (similar to the OnSectionTrack event of THeaderControl) and uses both HDN_TRACK and HDN_ITEMCHANGING to detect column changes.
This goes in the interface section of your unit:


type
 TdhColumnTrackEvent = procedure(Sender: TCustomListview; Column: TListColumn; Width: Integer; State: TSectionTrackState) of object;

TdhListView = class(TListview)
 private
  FColumnTrackEvent: TdhColumnTrackEvent;
 protected
  procedure WMNotify(var Msg: TWMNotify); message WM_NOTIFY;
 published
  property OnColumnTrack: TdhColumnTrackEvent read FColumnTrackEvent write FColumnTrackEvent;
end;


This goes in the implementation section:

procedure TdhListView.WMNotify(var Msg: TWMNotify);
var
 TrackState: TSectionTrackState;
 aColumn: TListColumn;
begin
 inherited;
 with Msg do
 case NMHdr^.code of
  HDN_BEGINTRACK, HDN_ENDTRACK, HDN_TRACK, HDN_ITEMCHANGING:
   begin
    case NMHdr^.code of
     HDN_BEGINTRACK: TrackState := tsTrackBegin;
     HDN_ENDTRACK: TrackState := tsTrackEnd;
    else
     TrackState := tsTrackMove;
    end;
   with PHDNotify(Pointer(NMHdr))^, PItem^ do
    if ((Mask and HDI_WIDTH) <> 0) then
     begin
      aColumn := Columns[Item];
       if Assigned(FColumnTrackEvent) then FColumnTrackEvent(self, aColumn, cxy, TrackState);
     end;
   end;
  end;
end;

Vienna again

It has been along time since I updated this blog. It seems that I have so many things to do, there is hardly any time left. Of course, it is always a matter of priorities, so you can figure how high this blog is on my list. Anyway, I was in Vienna in July, two times during the same month. Very hot weather. Vienna is a great city. For chocolates I recommend ‘Xokolat’, at Freyung 2 (Tel. 5354363). A large selection and not too expensive. I tried a 100% for the first time and I definitely do not recommend it; too bitter. I threw most of it away. However, the regular ones were excellent. The ‘Queen of Finland’ was kind enough to bring me some Fazer, which was very much appreciated. I guess we will see each other again in Berlin.

Thursday, February 16, 2006

Minus 25 degrees

Got back from Helsinki, after 4 days in the cold. I had a wonderful time and I have to thank the Queen of Finland once again (Jutti knows who I mean). I flew from Athens to Helsinki through Munich and I have to remember to avoid doing this in the future, because it seems that Munich has a tendency to get fogged-out in the winter, which leads to delays and cancellations. Fortunately I was lucky and had only half an hour of delay, which did not affect my arrival. Helsinki seemed out of this world. Everything frozen, snowing, landscape in black and white. I felt I had landed on another planet (e.g. Pluto). The next days were sunny, which, contrary to expectations (at least of those who live in milder climates) leads to lower temperatures (see title above). Some observations regarding these temperatures: snow does not melt, it just remains dust and gets blown by the wind like sand; also, do not touch metal doors or gates with bare hands (your hands will freeze and may get stuck on the cold metal). When I flew back and landed in Munich (transit), the minus 12 degrees there felt nice and warm.
Finland has the Fazer chocolates. I bought those with the chilli peppers and they were rather good, not too strong.

Thursday, September 29, 2005

My new Prius

I bought a Toyota Prius just a week ago. I have been procrastinating over it for a long time, but finally reminded myself that we only live once. My primary reason was environmental, but I suspect that, in the end, other reasons will prove equally important (especially torque). First of all, I must say that fuel consumption is around 5 lt/100km, but I am keeping a log and will have more reliable data on this during the next months. My previous car, a Citroen Xanthia 1800, needed around 9.5 lt/100km, and that was by driving very smoothly and shifting into neutral when going downhill. My wife’s Peugeot 406 (2 lt) goes at 10 lt/100km. Apart from fuel consumption, other nice things are:
The Prius has an automatic transmission, which works very well and handles all the ‘high-tech’ business of engaging the electric or conventional engine and charging the battery (this is shown on the LCD display and is great fun in the beginning). After a while, this high-tech feeling may fade away and I think that I will not take much notice. However, when looking at the other cars on the road, you are reminded that you are driving something different.
Torque is great! I can climb steep roads going as slowly as I wish with no fear of the engine stalling. If the battery is well charged, this can even work with the electric engine only, so there is no noise (‘vroom-vroom’) and no exhaust fumes (very nice, if you are in a garage). There is a rather steep road very close to my office, with traffic lights. When the green light turns on, most cars have trouble starting without rolling back a bit. The Prius is so easy.
The car is silent (completely silent) when going on battery power. This is great in my garage, but if you are driving on the street, pedestrians may not realize you are there, so take care.
Interior room is very comfortable. The trunk is a bit small.
Acceleration is also very good (by family car standards), but, when the conventional engine kicks in, there is some engine noise. This is probably more noticeable in the Prius than other cars, because most of the times it is not there.
Main negative: Price was rather high, at Euro 28.500. When I bought the car, I was certain that fuel economy would not compensate for this, because I was comparing the Prius with cars that cost around 15.000 to 20.000 Euro. But now I think that this is more of a car than I thought, so perhaps a more valid comparison would be with a larger car, say an Avensis (at around 25000 Euro).