gpt4 book ai didi

delphi - 如何在单击 TButton 时显示 TPopupMenu?

转载 作者:行者123 更新时间:2023-12-03 14:40:44 25 4
gpt4 key购买 nike

我想在点击按钮时显示一个弹出菜单,但是这个过程在Delphi XE中出现错误。

procedure ShowPopupMenuEx(var mb1:TMouseButton;var X:integer;var Y:integer;var pPopUP:TPopupMenu);
var
popupPoint : TPoint;
begin
if (mb1 = mbLeft) then begin
popupPoint.X := x ;
popupPoint.Y := y ;
popupPoint := ClientToScreen(popupPoint); //Error Here
pPopUP.Popup(popupPoint.X, popupPoint.Y) ;
end;
end;

procedure TForm1.Button1MouseUp(Sender: TObject; Button: TMouseButton;Shift: TShiftState; X, Y: Integer);
begin
ShowPopupMenuEx(button,Button1.Left,Button1.Top,PopupMenu1); //Error Here
end;

当点击按钮时显示此错误:

[DCC Error] Form1.pas(205): E2010 Incompatible types: 'HWND' and 'TPoint'
[DCC Error] Form1.pas(398): E2197 Constant object cannot be passed as var parameter
[DCC Error] Form1.pas(398): E2197 Constant object cannot be passed as var parameter

点击按钮时显示弹出菜单有更好的方法吗?

最佳答案

就这么做

procedure TForm1.Button1Click(Sender: TObject);
var
pnt: TPoint;
begin
if GetCursorPos(pnt) then
PopupMenu1.Popup(pnt.X, pnt.Y);
end;

更多讨论

如果您出于某种原因需要使用OnMosuseUp,您可以这样做

procedure TForm1.Button1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
pnt: TPoint;
begin
if (Button = mbLeft) and GetCursorPos(pnt) then
PopupMenu1.Popup(pnt.X, pnt.Y);
end;

您的代码不起作用,因为

  1. ClientToScreen 是带有签名的 Windows API 的函数

    function ClientToScreen(hWnd: HWND; var lpPoint: TPoint): BOOL;

    但是,还有一个带有签名的TControl.ClientToScreen

    function TControl.ClientToScreen(const Point: TPoint): TPoint;

    因此,如果您使用的是类方法,则该类是 TControl 的后代,ClientToScreen 将引用后者。如果没有,则引用前一个。当然,这个需要知道我们要从哪个窗口转换坐标!

  2. 此外,如果您声明

    var mb1: TMouseButton

    作为参数,则仅接受 TMouseButton 类型的变量。但我看不出您有任何理由想要您的 ShowPopupMenuEx 函数的签名。事实上,我认为根本不需要这样的功能......

替代方案

我上面的代码将在光标位置弹出菜单。如果您需要相对于按钮的一个角固定该点,您可以这样做

// Popup at the top-left pixel of the button
procedure TForm1.Button1Click(Sender: TObject);
begin
with Button1.ClientToScreen(point(0, 0)) do
PopupMenu1.Popup(X, Y);
end;

// Popup at the bottom-right pixel of the button
procedure TForm1.Button1Click(Sender: TObject);
begin
with Button1.ClientToScreen(point(Button1.Width, Button1.Height)) do
PopupMenu1.Popup(X, Y);
end;

// Popup at the bottom-left pixel of the button
procedure TForm1.Button1Click(Sender: TObject);
begin
with Button1.ClientToScreen(point(0, Button1.Height)) do
PopupMenu1.Popup(X, Y);
end;

关于delphi - 如何在单击 TButton 时显示 TPopupMenu?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3986999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com