c# 在winform 标题栏 显示菜单
时间: 2023-08-07 12:05:56 浏览: 192
在WinForms中,可以通过覆盖窗体的CreateParams属性来实现在窗体标题栏上显示菜单。
以下是实现步骤:
1. 在窗体的CreateParams属性中添加标题栏菜单样式:
```c#
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
// 添加标题栏菜单样式
cp.Style |= 0x00000040; // WS_CAPTION | WS_SYSMENU
return cp;
}
}
```
2. 在窗体的HandleCreated事件中添加菜单:
```c#
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
// 添加菜单
IntPtr hMenu = GetSystemMenu(this.Handle, false);
int menuItemCount = GetMenuItemCount(hMenu);
InsertMenu(hMenu, menuItemCount, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty);
InsertMenu(hMenu, menuItemCount + 1, MF_BYPOSITION, 0x007B, "菜单项");
}
```
其中,GetSystemMenu函数用于获取窗体的系统菜单句柄,GetMenuItemCount函数用于获取菜单项数量,InsertMenu函数用于插入菜单项。在这里,我们插入了一个分隔符和一个菜单项,菜单项的标识符为0x007B。
完整代码如下:
```c#
public partial class Form1 : Form
{
private const int MF_BYPOSITION = 0x00000400;
private const int MF_SEPARATOR = 0x00000800;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetMenuItemCount(IntPtr hMenu);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool InsertMenu(IntPtr hMenu, int uPosition, int uFlags, int uIDNewItem, string lpNewItem);
public Form1()
{
InitializeComponent();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
// 添加标题栏菜单样式
cp.Style |= 0x00000040; // WS_CAPTION | WS_SYSMENU
return cp;
}
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
// 添加菜单
IntPtr hMenu = GetSystemMenu(this.Handle, false);
int menuItemCount = GetMenuItemCount(hMenu);
InsertMenu(hMenu, menuItemCount, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty);
InsertMenu(hMenu, menuItemCount + 1, MF_BYPOSITION, 0x007B, "菜单项");
}
}
```
运行程序后,可以看到在窗体的标题栏上显示了菜单项。
阅读全文