delphi - 当用键盘打开弹出窗口时,如何使 Tpopupmenu 预选第一个菜单项

标签 delphi winapi delphi-7 delphi-2010

TPopupMenu 中的项目可以用键盘或鼠标高亮/选择。使用键盘选择时,您可以使用箭头键在菜单中移动。

如何在不使用 VK_DOWN 模拟向下箭头按键的情况下将第一个菜单项标记为选中(蓝色)(参见下面的代码)?

Popup := TPopupMenu.create(nil);
Popup.OnPopup := PopupClick;
class procedure TTrayMain.PopupClick(Sender: TObject) ;
begin    
  // Code below activates the first menu entry.. 
  // Now Looking for an alternative solution to replace this hack:
  keybd_event( VK_DOWN, MapVirtualKey( VK_DOWN,0), 0, 0);
  keybd_event( VK_DOWN, MapVirtualKey( VK_DOWN,0), KEYEVENTF_KEYUP, 0);

end;

最佳答案

您需要将未记录的 MN_SELECITEM 消息发送到弹出窗口。

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Menus, ExtCtrls, StdCtrls;

type
  TForm1 = class(TForm)
    PopupMenu1: TPopupMenu;
    Item1: TMenuItem;
    Item2: TMenuItem;
    Item3: TMenuItem;
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  //To override the default PopupList, based on Remy Lebeau's code
  TPopupListEx = class(TPopupList)
  protected
    procedure WndProc(var Message: TMessage); override;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

const MN_SELECTITEM = $01E5;

{ TPopupListEx }

procedure TPopupListEx.WndProc(var Message: TMessage);
var hm:HMENU;

begin
  inherited;
  if (Message.Msg = WM_ENTERMENULOOP) and (Message.WParam = 1) then
    begin
      //When the popupwindow is already created, we can ask it's handle
      hm:=FindWindow(PChar('#32768'),nil);
      //Send the MN_SELECTITEM message. The third parameter is the desired menuitem's index.
      SendMessage(hm,MN_SELECTITEM,0,0);
    end;
end;

initialization
  Popuplist.Free; //free the "default", "old" list
  PopupList := TPopupListEx.Create; //create the new one
  // The new PopupList will be freed by
  // finalization section of Menus unit.
end.

注意其他(包括提到的 delphipraxis 示例)解决方案:

使用 SetMenuItemInfoWHiliteMenuItem 将 MenuItem 设置为高亮状态将不起作用,因为它只会影响外观,但是当您悬停鼠标时在任何其他项目上,第一个项目保持突出显示。

关于delphi - 当用键盘打开弹出窗口时,如何使 Tpopupmenu 预选第一个菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71480072/

相关文章:

delphi - Delphi 可以告诉我引发异常的例程的名称吗?

delphi - 标准对话框不弹出

delphi - Delphi 2007 for Win32 (Enterprise) 帮助系统可以在 Windows 7 Ultimate 32 位下运行吗?

c++ - 从 png、winapi 创建透明图像

delphi - 如何获得笔记本电脑或台式机支持的最大内存大小?

arrays - 类的函数返回一个在类之后声明的数组

delphi - 如何在 2009 年之前的 Delphi 中解码包含日语字符的 url?

windows - 什么会导致节句柄泄漏?

c++ - 将扫描码发送到我的应用程序

Delphi Loadlibrary 返回 0 (LastErrorcde=3221225616) 这是什么意思?