2005. május 15., vasárnap

How to add items to a program's system menu


Problem/Question/Abstract:

How to add items to a program's system menu

Answer:

Solve 1:

unit Unit1;

interface

uses
  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, Menus;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    procedure winmsg(var msg: TMsg; var handled: boolean);
    {This is what handles the messages}
    procedure Anything; {Procedure to do whatever}
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

const
  ItemID = 99; {The ID number for your menu item - can be anything}

procedure TForm1.winmsg(var msg: TMsg; var handled: boolean);
begin
  {If the message is a system one ...}
  if msg.message = WM_SYSCOMMAND then
    {... then check if its parameter is your Menu items ID}
    if msg.wparam = ItemID then
      Anything;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  application.onmessage := winmsg;
  {Tell your app that 'winmsg' is the application message handler}
  AppendMenu(GetSystemMenu(form1.handle, false), mf_separator, 0, '');
  {Add a seperator bar to form1}
  AppendMenu(GetSystemMenu(form1.handle, false), mf_byposition, ItemID, '&New Item');
  {Add your menu item to form1}
  AppendMenu(GetSystemMenu(application.handle, false), mf_separator, 0, '');
  {Add a seperator bar to the application system menu(used when app is minimized)}
  AppendMenu(GetSystemMenu(application.handle, false), mf_byposition, ItemID, '&New Item');
  {Add your menu itemto the application system menu(used when app is minimized)}
end;

procedure TForm2.Anything;
begin
  {Add whatever you want to this procedure}
end;

end.


Solve 2:

First, you need to add the items to the existing system menu:


var
  SysMenu: HMenu;
  { ... }
  SysMenu := GetSystemMenu(Handle, False);
  { Note: the low order four bits of the command values must be 0 }
  AppendMenu(SysMenu, mf_String or mf_ByPosition, $F210, 'New Item 1');
  AppendMenu(SysMenu, mf_String or mf_ByPosition, $F220, 'New Item 2');
  { ... }


Then you need a message handler for the WM_SYSCOMMAND message:


procedure WMSysCommand(var MSg: TWMSysCommand); message WM_SYSCOMMAND;


Which you implement like so:


procedure TForm1.WMSysCommand(var MSg: TWMSysCommand);
begin
  inherited;
  case Msg.CmdType of
    $F210:
      begin
        { Handle new item 1 here }
        ShowMessage('New Item 1');
      end;
    $F220:
      begin
        { Handle new item 2 here }
        ShowMessage('New Item 2');
      end;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése