Library code snippets

Modify a Window's System Menu

I wanted to keep the SiteWatcher utility as streamlined as possible. There really isn't a need for a cumbersome menu hierarchy or flashy toolbar. But I didn't want to release an application without crediting myself! So I simply added an About SiteWatcher item to the application window's system menu.

Adding an item to the system menu is quite easy once you discover a couple of existing User32 functions. A little Interop... and... voila!

You do have to remember to override the WndProc method so you can inject your own custom handler when the menu item is clicked.

  using System.Runtime.InteropServices;
 
  [DllImport("user32.dll")]
  private static extern int GetSystemMenu (int hwnd, int bRevert);
 
  [DllImport("user32.dll")]
  private static extern int AppendMenu (
    int hMenu,int Flagsw,int IDNewItem,string lpNewItem);
 
  private void SetupSystemMenu ()
  {
    // get handle to system menu
    int menu = GetSystemMenu(this.Handle.ToInt32(),0);
    // add a separator
    AppendMenu(menu,0xA00,0,null);
    // add an item with a unique ID
    AppendMenu(menu,0,1234,"About SiteWatcher");
  }
 
  protected override void WndProc (ref Message m)
  {
    base.WndProc(ref m);
    // WM_SYSCOMMAND is 0x112
    if (m.Msg == 0x112)
    {
      // check for my new menu item ID
      if (m.WParam.ToInt32() == 1234)
      {
        // show About box here...
      }
    }
  }

Comments

  1. 31 Dec 2006 at 09:44

    Hi,

    I tryed to do this with .NET 2.0 and VS 2005 in C#: I've added the three lines code to add a separator and a menu item in the form class constructor directly after the InitializeComponent call. After running the project I couldn't see any changes made to the forms system menu.

    The problem was I tryed to modify the menu too early. It seems to work only after the form has been visible.

    nd

  2. 01 Jan 1999 at 00:00

    This thread is for discussions of Modify a Window's System Menu.

Leave a comment

Sign in or Join us (it's free).

Steven Cohn
AddThis

Related discussion

Related podcasts

  • Object-Oriented Programming in Ruby

    In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...

Events coming up

  • Aug 28

    St. Louis Day of .NET

    St. Charles, United States

    Technical conference with be 2 full days of content with over 40 sessions from local and national speakers, with topics such as:•.NET languages: C#, VB.NET•Technologies: WPF, Silverlight, WCF•Development tools: Visual Studio, TFS, Expression Blend

Want to stay in touch with what's going on? Follow us on twitter!