From: keeper@mindspring.com (Mark R. Johnson)
Subject: Re: Tip o' the day!
Date: Mon, 17 Jul 95 05:35:48 GMT

I have managed to get around some of these types of problems
with using OnXXXX event handlers by declaring user messages
and then posting them to my program's message queue.

For example, I modified the Delphi TextDemo program to report
the line and column position of the cursor.  To keep it up to
date, I wanted it to be triggered by the OnKeydown event of
the TMemo.  However, OnKeydown fires before the key is
interpretted, so the position reported will be the position
of the cursor just before the PgUp/Up-Arrow/whatever was
pressed (i.e. an obsolete value).  To have the cursor position
determined AFTER the keydown, I did something like the following:

const
  um_UpdatePosition = WM_USER + 0;

type
  TForm1 = class(TForm)
    ...
    procedure memEditKeyDown(...);
  protected
    procedure UMUpdatePosition(var message: TMessage);
    ...
  end;

implementation

procedure TForm1.memEditKeyDown(...);
begin
  PostMessage(Handle, um_UpdatePosition, 0, 0);  {put message on queue}
end;

procedure TForm1.UMUpdatePosition(var message : TMessage);
begin
  {calculate cursor position}
  {display new position}
end;

end.

This organization allows the KeyDown to finish being processed
during which time the cursor is usually moved.  Then the
um_UpdatePosition message is pulled off the message queue and
dispatched to my UMUpdatePosition() procedure which calculates
the new position.  As a result, the cursor position is always
updated correctly and immediately, even when a key is pressed
and held down until it repeats.  (KeyUp would not fire until the
key was finally released.)

This technique may seem a little strange to Visual Basic and
Delphi users, but it is perfectly natural to native Windows
applications.  I highly recommend it.  (And it doesn't use
one of the few Windows timers that are available.)

--Mark Johnson

______________________________________________________________________________
 Mark R. Johnson       _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_
 Atlanta, GA USA       _/  http://www.mindspring.com/~cityzoo/cityzoo.html  _/
 keeper@mindspring.com _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
