在C++中将自定义项添加到系统菜单,可以通过以下步骤实现:
#include<Windows.h>
// 创建一个新的菜单项
HMENU hMenu = CreateMenu();
// 添加自定义菜单项
AppendMenu(hMenu, MF_STRING, ID_MY_MENU_ITEM, TEXT("My Custom Menu Item"));
// 获取系统菜单句柄
HWND hWnd = GetDesktopWindow();
HMENU hSysMenu = GetSystemMenu(hWnd, FALSE);
// 将自定义菜单项添加到系统菜单
InsertMenu(hSysMenu, 0, MF_BYPOSITION | MF_POPUP, (UINT_PTR)hMenu, TEXT("My Custom Menu"));
// 处理菜单项点击事件
switch (LOWORD(wParam)) {
case ID_MY_MENU_ITEM:
// 自定义菜单项被点击时执行的代码
break;
}
完整的代码示例:
#include<Windows.h>
// 自定义菜单项ID
#define ID_MY_MENU_ITEM 1000
// 窗口过程函数
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_CREATE:
// 创建一个新的菜单项
HMENU hMenu = CreateMenu();
// 添加自定义菜单项
AppendMenu(hMenu, MF_STRING, ID_MY_MENU_ITEM, TEXT("My Custom Menu Item"));
// 获取系统菜单句柄
HMENU hSysMenu = GetSystemMenu(hWnd, FALSE);
// 将自定义菜单项添加到系统菜单
InsertMenu(hSysMenu, 0, MF_BYPOSITION | MF_POPUP, (UINT_PTR)hMenu, TEXT("My Custom Menu"));
break;
case WM_SYSCOMMAND:
// 处理菜单项点击事件
switch (LOWORD(wParam)) {
case ID_MY_MENU_ITEM:
// 自定义菜单项被点击时执行的代码
MessageBox(hWnd, TEXT("My Custom Menu Item Clicked"), TEXT("Notification"), MB_OK);
break;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// 注册窗口类
WNDCLASSEX wc = {0};
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = TEXT("MyWindowClass");
RegisterClassEx(&wc);
// 创建窗口
HWND hWnd = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("MyWindowClass"), TEXT("My Window"),
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 500, 300, NULL, NULL, hInstance, NULL);
// 显示窗口
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// 消息循环
MSG msg = {0};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
这样就可以在C++中将自定义项添加到系统菜单了。
领取专属 10元无门槛券
手把手带您无忧上云