How can I add a new menu item to the system menu application?

How can I add a new menu item to the system menu application?

How can I add a new menu item to the systemmenu application?


Forthe most part, you’ll never have a need for this. But it is useful for setting a form style, or some other action that is more system-oriented than application-oriented.

If you’ve tried to do this before but couldn’t, it’s because there is noway to add a menu item with standard Delphi calls. You have to trap the Windows message WM_SYSCOMMAND and evaluate the wParam messageelement to see if your added menu item was selected. It’s notthat hard, and a little digging in the API help was all I needed to do to findout how to implement this in a program.

  1. Create a new form.
  2. Override the OnMessage event by assigning a new event handler procedurefor the OnMessage event.
  3. Create a constant that will be used as the ordinal identifier for yourmenu choice.
  4. In the FormCreate, make your menu choice with the AppendMenu API call.
Here’s the code to show you how to do it:
unit sysmenu;interfaceuses  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,  Forms, Dialogs, Menus;type  TForm1 = class(TForm)    procedure FormCreate(Sender: TObject);  private    { Private declarations }  public     {This declaration is of the type TMessageEvent, which is a pointer to a      procedure that takes two variable arguments of type TMsg and Boolean,respectively.}     procedure WinMsgHandler(var Msg : TMsg; var Handled : Boolean);  end;var  Form1: TForm1;const  MyItem = 100; {Here’s the menu identifier. It can be any WORD value}implementation{$R *.DFM}procedure TForm1.FormCreate(Sender: TObject);begin  {First, tell the application that its message handler is different fromthe default}  Application.OnMessage := WinMsgHandler;  {Add a separator}  AppendMenu(GetSystemMenu(Self.Handle, False), MF_SEPARATOR, 0, ”);  {Add your menu choice. Since the Item ID is high, using the MF_BYPOSITION   constant will place it last on the system menu}  AppendMenu(GetSystemMenu(Self.Handle, False), MF_BYPOSITION, MyItem, ‘MyMen&u Choice’);end;procedure TForm1.WinMsgHandler(var Msg : TMsg; var Handled : Boolean);begin  if Msg.Message=WM_SYSCOMMAND then {if the message is a system one…}   if Msg.wParam = MyItem then     {Put handling code here. I’ve opted for a ShowMessage fordemonstration purposes}     ShowMessage(‘You picked my menu!’);end;end.

As you can see, this is fairly straightforward. It opens up many doors tothings you can do. In anticipation of some questions you might have later,The AppendMenu command can also be used with minimized apps. For instance,if you minimize your app, the icon represents the application, not yourform. To make the system menu with your changes visiblewhen in minimized form, you would use Application.Handle instead ofSelf.Handle to deal with the application’s system menu.


Share the Post: