Right justify a main menu item

If you use standard main menu component, all items are usually on the left side of the window and there is not much you can do about it using Object Inspector. Here is a little trick to move one main menu item on the right side while the rest remains on the left side. It’s usually useful for “Help” or “About” items.

Put a main menu component with few items on the form. Name one of it Help1 and put the following code into OnCreate event of main form.

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    MainMenu1: TMainMenu;
    est11: TMenuItem;
    est21: TMenuItem;
    est111: TMenuItem;
    est211: TMenuItem;
    Help1: TMenuItem;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var MItem: TMenuItemInfo;
    Buf: Array[0..79] of Char;
begin
  ZeroMemory(@MItem, SizeOf(MItem));
  with MItem do
  begin
    cbSize := 44;
    fMask := MIIM_TYPE;
    dwTypeData := Buf;
    cch := SizeOf(Buf);
  end;

  if GetMenuItemInfo(MainMenu1.Handle, Help1.MenuIndex, True, MItem) then
  begin
    MItem.fType := MItem.fType or MFT_RIGHTJUSTIFY;
    if SetMenuItemInfo(MainMenu1.Handle, Help1.MenuIndex, True, MItem) then DrawMenuBar(MainMenu1.WindowHandle);
  end;
end;

end.

Leave a Reply