Delphi实现点击按钮触发选择项, 进而实现不同的分支功能
程序员文章站
2023-12-22 16:45:46
...
1.实现按钮右击事件触发选择项
添加一个TPopupMenu控件,设置按钮的PopupMenu属性为新增的TPopupMenu控件,即可完成右击出现选择项。
2.实现按钮左击事件触发选择项
添加一个TPopupMenu控件pm3,在按钮的Click事件中如下代码,即可完成左击出现选择项。
procedure TfrmMain.rzbtbtn3Click(Sender: TObject);
var
lppoint: Tpoint;
begin
GetCursorPos(lppoint);
pm3.Popup(lppoint.x, lppoint.y);
end;
3.实现按钮左击事件触发选择项(进阶:代码实现添加TPopupMenu控件及选择项)
添加一个TPopupMenu控件pm3,在按钮的Click事件中如下代码,即可完成左击出现选择项。
procedure TForm1.rzbtbtn3Click(Sender: TObject);
var
lppoint: Tpoint;
_PopupMenuTemp : TPopupMenu; //use Menus;
_MenuItemTemp : TMenuItem;
begin
try
_PopupMenuTemp := TPopupMenu(Self.FindComponent('PopupMenuTemp'));
if _PopupMenuTemp = nil then
begin
//Self:当Self释放时自动触发释放 https://blog.csdn.net/weixin_41660162/article/details/79828668
_PopupMenuTemp := TPopupMenu.create(Self);
_PopupMenuTemp.Name := 'PopupMenuTemp';
_MenuItemTemp := TMenuItem.Create(_PopupMenuTemp);
_PopupMenuTemp.Items.Add(_MenuItemTemp);
_MenuItemTemp.Caption := '自定义生成的Item1';
_MenuItemTemp.OnClick := MenuItemTempClick;
_MenuItemTemp := TMenuItem.Create(_PopupMenuTemp);
_PopupMenuTemp.Items.Add(_MenuItemTemp);
_MenuItemTemp.Caption := '自定义生成的Item2';
_MenuItemTemp.OnClick := MenuItemTempClick;
end;
GetCursorPos(lppoint);
_PopupMenuTemp.Popup(lppoint.x, lppoint.y);
finally
//if Assigned(_PopupMenuTemp) then _PopupMenuTemp.Destroy;
end;
end;
procedure TForm1.MenuItemTempClick(Sender: TObject);
begin
ShowMessage((Sender as TMenuItem).Caption);
end;