我有一个 WinForms 应用程序,我想向用户单击窗口左上角(图标)或按 ALT+SPACE 时打开的菜单添加一个菜单项。
表单只显示一个 MainMenu 和一个 ContextMenu,但没有 SystemMenu 或类似的东西。有没有一种简单的方法可以在 WinForms 应用程序上修改它?
我想添加一个简单的“关于”条目,仅供人们从应用程序内检查版本和 URL。通常的 UI 中没有合适的位置(没有主菜单)。
最佳答案
当您将 FormBorderStyle 设置为除“None”之外的任何值时,此菜单将添加到表单中。当表单边框样式改变时,调用一个名为AdjustSystemMenu 的例程。该例程使用 GetSystemMenu 方法来检索 SystemMenu?从某个地方。 “某处”就是问题所在。似乎没有任何可以访问的 SystemMenu 对象。
编辑: 刚刚发现这个link ,看起来它可能会做你想要的。
public partial class Form1 : 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 = 0x0;
#endregion
// The constants we'll use to identify our custom system menu items
public const Int32 _SettingsSysMenuID = 1000;
public const Int32 _AboutSysMenuID = 1001;
public Form1()
{
InitializeComponent();
}
private void Form1_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
InsertMenu(systemMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty); // <-- Add a menu seperator
InsertMenu(systemMenuHandle, 6, MF_BYPOSITION, _SettingsSysMenuID, "Settings...");
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);
}
}
关于.net - 在 WinForms 中向系统菜单(左上角图标菜单)添加条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1235258/