Home > OS >  How can I add an item with icon in the system menu of a form?
How can I add an item with icon in the system menu of a form?

Time:10-18

This is my code that works except for the icon

procedure TForm1.FormCreate(Sender: TObject);
var item : TMenuItemInfo;
begin
  with item do
  begin
    cbSize := SizeOf(MenuItemInfo);
    fMask := MIIM_TYPE or MIIM_ID;
    fType := MFT_STRING;
    wID := 180;
    dwTypeData := PChar('Test');
    cch := 4;
    hbmpItem := Image1.Picture.Bitmap.Handle;  //Image1 is TImage
  end;
  InsertMenuItem(GetSystemMenu(Handle, FALSE),0,true,item);
end;

CodePudding user response:

A couple of issues:

  1. You don't clear the TMenuItemInfo instance before use. Unassigned fields may contain invalid or erroneous data when the call is made.

    Use

    ZeroMemory(@item, SizeOf(item));

    at the beginning of the procedure.

  2. The combination of fMask and fType members you have is incorrect.

    Use the following instead

    fMask := MIIM_STRING or MIIM_BITMAP or MIIM_ID;
    //  fType := MFT_STRING;
    

    That is, don't assign fType

Here is a sample snip of a test, where a TImage holds the image depicting a number 2 on orange background. That is added as icon to the new menu item. (Which is your question)

enter image description here

Adding test code as requested:

// Note! Your `Image1` must have a bitmap loaded
procedure TForm39.AddSystemMenuItem;
var
  item : TMenuItemInfo;
begin
  ZeroMemory(@item, SizeOf(item));
  with item do
  begin
    cbSize := SizeOf(MenuItemInfo);
    fMask := MIIM_STRING or MIIM_BITMAP or MIIM_ID;
    // fType := MFT_STRING;
    wID := 180;
    dwTypeData := PChar('Test');
    cch := 4;
    hbmpItem := Image1.Picture.Bitmap.Handle;  //Image1 is TImage
  end;
  if not InsertMenuItem(GetSystemMenu(Handle, FALSE),0,true,item) then
    ShowMessage('Failed');
end;

procedure TForm39.Button1Click(Sender: TObject);
begin
  AddSystemMenuItem;
end;
  • Related