2010. június 28., hétfő

How to control where text is dropped into a TMemo


Problem/Question/Abstract:

How can I control where text is dropped into a TMemo? In other words, I am in the middle of a drag operation and want to drop selected text into a TMemo based on the mouse position of where I drop. How can I tell the caret to go to the mouse location prior to the drop action?

Answer:

Send a EM_CHARFROMPOS message to the control, passing the mouse position (in client coordinates).

procedure TForm1.Memo1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
  ret: Longint;
begin
  ret := memo1.perform(EM_CHARFROMPOS, 0, MakeLParam(X, Y));
  label1.caption := format('row: %d, character index: %d', [HiWord(ret),
    LoWord(ret)]);
end;

That is the first step, it gives you the mouse position in "character coordiantes". You still need to convert that to a character index, which you assign to SelStart to set the caret to that position.

with memo1 do
  selstart := perform(EM_LINEINDEX, row, 0) + col;

You can now assign the dropped text to the memos SelText property to insert it.

Note that the EM_CHARFROMPOS message can also be used with TRichedit but the parameters
are different!

Nincsenek megjegyzések:

Megjegyzés küldése