Doug Hay wrote:
I want to Popup a TPopupMenu when the mouse is over a TLabel. This
part is easy. But when I move the mouse off of the TLabel I want to
close the TPopupMenu.
And what do you think is going to happen when the user tries to move
the mouse off of the Label to roll over the popup menu or click on
item? You need to account for that.
I've tried a few things, like sending a message simulating that the
ESC key was pressed. Not sure what else to try.
Basically, you have to track the mouse manually and then dismiss the
popup menu when the mouse is no longer in an area you want. For
example, a similar question was asked on StackOverflow a couple of
years ago:
Automatically Hide or Close PopUp Menu when Mouse Pointer is outside it
https://stackoverflow.com/questions/38739794/
I answered with code that was designed to make a TPopupMenu "close when
the user moves the Mouse Pointer out of it for more than two or three
seconds" and to "be closed after five minutes". In a nutshell, the
code starts a timer when the PopupMenu is shown and stops the timer
when the menu is dismissed, and inside the timer it checks if the mouse
is over the menu, and if not then dismisses the menu after a timeout
period. You can tweak the code to remove the timeout logic, and make
it dismiss only when the mouse is not over the Label or the PopupMenu.
For example:
procedure TForm1.Label1MouseEnter(Sender: TObject);
begin
SetForegroundWindow(Handle);
with Mouse.CursorPos do
PopupMenu1.PopUp(X, Y);
PostMessage(Handle, WM_NULL, 0, 0);
Timer1.Enabled := False;
end;
procedure TForm1.PopupMenu1Popup(Sender: TObject);
begin
Timer1.Enabled := True;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
hPopupWnd: HWND;
R: TRect;
Pt: TPoint;
begin
hPopupWnd := FindWindow('#32768', nil);
if hPopupWnd = 0 then Exit;
GetWindowRect(hPopupWnd, R);
InflateRect(R, 2, 2);
GetCursorPos(Pt);
if not PtInRect(R, Pt) then
begin
R := Label1.BoundsRect;
MapWindowPoints(Label1.Parent.Handle, 0, R, 2);
if not PtInRect(R, Pt) then
SendMessage(PopupList.Window, WM_CANCELMODE, 0, 0);
end;
end;
--
Remy Lebeau (TeamB)
Connect with Us