2011/10/11

[C#] Form App 의 System Menu에 사용자 메뉴 추가하기

C#의 Windows Form Application에서 System 메뉴에 사용자 메뉴를 추가하는 방법이다. 인터넷을 통해 알게된 방법으로 Add System Menu Items to a Form using Windows API 글을 보고 알게 되었다. C# 에서의 Win32 API 사용과 메세지 핸들링에 대한 지식을 알고 있어야 겠다. C++에서는 API 사용이 쉬웠는데 그 C#에서는 다소 복잡해 보인다.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

// For Custom System Menu
// using System;
// using System.Windows.Forms;
// using System.Runtime.InteropServices;

namespace MyFormApp
{
public partial class frmMain : Form
{
#region Win32 API Stuff
// Define the Win32 API methods we are going to use
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

[DllImport("user32.dll")]
private static extern bool InsertMenu(IntPtr hMenu, Int32 wPosition,
Int32 wFlags, Int32 wIDNewItem, string lpNewItem);

/// Define our Constants we will use
public const Int32 WM_SYSCOMMAND = 0x112;
public const Int32 MF_SEPARATOR = 0x800;
public const Int32 MF_BYPOSITION = 0x400;
public const Int32 MF_STRING = 0x000;
#endregion

// The constants we'll use to identify our custom system menu items
public const Int32 _SettingsSysMenuID = 1000;
public const Int32 _AboutSysMenuID = 1001;

public frmMain()
{
InitializeComponent();
}

private void frmMain_Load(object sender, EventArgs e)
{
/// Get the Handle for the Forms System Menu
IntPtr systemMenuHandle = GetSystemMenu(this.Handle, false);

/// Create our new System Menu items just before the Close menu item
// Add a menu seperator
InsertMenu(systemMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR,
0, string.Empty);
// Add Settings Menu
InsertMenu(systemMenuHandle, 6, MF_BYPOSITION,
_SettingsSysMenuID, "Settings...");
// Add About Menu
InsertMenu(systemMenuHandle, 7, MF_BYPOSITION,
_AboutSysMenuID, "About...");
}

protected override void WndProc(ref Message m)
{
// Check if a System Command has been executed
if (m.Msg == WM_SYSCOMMAND)
{
/// Execute the appropriate code for
/// the System Menu item that was clicked
switch (m.WParam.ToInt32())
{
case _SettingsSysMenuID:
MessageBox.Show("\"Settings\" was clicked");
break;
case _AboutSysMenuID:
MessageBox.Show("\"About\" was clicked");
break;
}
}

base.WndProc(ref m);
}
}
}



실행 결과 화면

실행 결과 화면

<

Original Post : http://neodreamer-dev.tistory.com/587

No comments :

Post a Comment