How to Pop-up Form on Right Click?
I need to be able to pop-up a TForm when I right click on a TPaintBox (the content of the form will be dependent upon where I click). If the user clicks an开发者_如何转开发ywhere else I'd like the original form to be destroyed (or at least disappear). If the new click happens to be another right-click on the TPaintBox, a new TForm must appear. Basically, it's a right-click properties query type action i.e. right-click to get the properties of the area of the TPaintBox.
This seems to be more difficult than I imagined. I first tried to destroy the pop-up form when the pop was deactivated using the OnDeactivate event. This resulted in the popup not being shown.
Here's my solution (tested and working)...
type
TForm1 = class(TForm)
...
private
ContextForm: TfrmContext;
end;
...
implementation
procedure TForm1.Button1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if ContextForm <> nil then
FreeAndNil(ContextForm);
if Button = mbRight then
begin
ContextForm := TfrmContext.Create(Application);
ContextForm.SetParentComponent(Application);
ContextForm.Left := Mouse.CursorPos.X;
ContextForm.Top := Mouse.CursorPos.Y;
ContextForm.Show;
end;
end;
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if ContextForm <> nil then
FreeAndNil(ContextForm);
end;
In this demo, a right-click on Button1 will create your "Context Form" (which is a TForm) and set its position so the top-left of your "context form" will sit exactly where your mouse cursor is.
A click anywhere else on your form will destroy the Context Form.
Enjoy!
精彩评论