Delphi计算TPopupMenu的大小

问题描述

我有一个按钮,单击后显示弹出菜单。在下面或右边有两个选项。

如果屏幕足够大,那就轻松

针对以下内容

Pt := Self.ClientToScreen(self.ClientRect.TopLeft);
pt.Y := pt.Y + Self.Height;
PopupMenu.Popup( pt.X,pt.Y);

正确:

Pt := Self.ClientToScreen(self.ClientRect.TopLeft);
Pt.X := PT.X + Self.Width;
PopupMenu.Popup( pt.X,pt.Y);

但是问题是,当屏幕上没有足够的空间用于该操作时。在这种情况下,弹出菜单自动定位,但位于按钮上方。我不要那个。如果下面没有空间,我想在上面。但是为此,我需要高度和宽度。

高度计算:

 Function getPopUpHeight: Integer;
  var i: Integer;
      tmpHeight: Integer;
  begin
    result := 0;
    tmpHeight := 0;
    Self.Canvas.Font := Screen.MenuFont;
    for i := PopupMenu.items.count - 1 downto 0 do begin
    //do for all items
    if PopupMenu.Items[i].Visible then begin //process visible
        if (PopupMenu.Items[i].IsLine OR (PopupMenu.Items[i].Caption = '-')) then begin
          //if seperator line
          tmpHeight:= 6;
          result := result + tmpHeight;
        end else begin
          //if actual item
          result := result + Self.Canvas.TextHeight(PopupMenu.Items[i].Caption) + 6 ;
        end;
      end;
    end;
  end;

宽度计算

  Function GetPopupWidth: Integer;
  var i,lStLine:integer;
  begin
    result := 0;
    lStLine := 0;
    self.Canvas.Font.Size := Screen.MenuFont.Size;
    for i:=0 to PopupMenu.Items.Count-1 do begin
    if PopupMenu.Items[i].Visible then begin
      if (PopupMenu.Items[i].IsLine OR (PopupMenu.Items[i].Caption = '-')) then begin
        inc(lStLine);
      end else begin
        if result < (self.Canvas.TextWidth(PopupMenu.items[i].Caption) + 9) then begin
         result := Self.Canvas.TextWidth(PopupMenu.items[i].Caption) + 9;
        end;
      end;
    end;
    end;
    if lStLine > 0 then begin
    result := result + 58;
    end;
  end;

但是我的计算中缺少一些东西,因为有时会出现随机行为,有时却是正确的。有时是高价,有时是低价。

知道我在做什么错或忘记吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)