用c++代码写win32 做一简单窗口,添加一个“非模式对话框”菜单项,当用户点击该菜单项时,在主菜单条下添加一个弹出式菜单“对话框”,下面有菜单项,分别为“打开”、“关闭”、分隔线和“删除菜单”,初始情况下“删除菜单”为不可用
时间: 2023-11-16 19:06:25 浏览: 56
这是一个编程问题,可以直接回答。以下是一个简单的 C 代码示例,实现了一个窗口和一个非模式对话框菜单项,当用户点击该菜单项时,在主菜单条下添加一个弹出式菜单“对话框”,包含“打开”、“关闭”和“删除菜单”菜单项,初始情况下“删除菜单”为不可用。
```c
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// Register the window class
const char CLASS_NAME[] = "Sample Window Class";
WNDCLASS wc = {0};
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Create the window
HWND hWnd = CreateWindowEx(
0, // Optional window styles
CLASS_NAME, // Window class
"Sample Window", // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hWnd == NULL)
{
return 0;
}
// Show the window
ShowWindow(hWnd, nCmdShow);
// Run the message loop
MSG msg = {0};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static HMENU hPopupMenu = NULL;
static BOOL bMenuEnabled = FALSE;
switch (message)
{
case WM_CREATE:
{
// Create the popup menu
hPopupMenu = CreatePopupMenu();
AppendMenu(hPopupMenu, MF_STRING, ID_OPEN, "打开");
AppendMenu(hPopupMenu, MF_STRING, ID_CLOSE, "关闭");
AppendMenu(hPopupMenu, MF_SEPARATOR, 0, NULL);
AppendMenu(hPopupMenu, MF_STRING | MF_DISABLED, ID_DELETE, "删除菜单");
return 0;
}
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case ID_DIALOG:
{
// Add the popup menu to the main menu
HMENU hMenu = GetMenu(hWnd);
if (hMenu != NULL)
{
InsertMenu(hMenu, -1, MF_BYPOSITION | MF_POPUP, (UINT_PTR)hPopupMenu, "对话框");
bMenuEnabled = TRUE;
EnableMenuItem(hPopupMenu, ID_DELETE, MF_ENABLED);
DrawMenuBar(hWnd);
}
return 0;
}
case ID_OPEN:
{
// Handle the "打开" menu item
MessageBox(hWnd, "打开", "提示", MB_OK);
return 0;
}
case ID_CLOSE:
{
// Handle the "关闭" menu item
MessageBox(hWnd, "关闭", "提示", MB_OK);
return 0;
}
case ID_DELETE:
{
// Handle the "删除菜单" menu item
HMENU hMenu = GetMenu(hWnd);
if (hMenu != NULL)
{
RemoveMenu(hMenu, -1, MF_BYPOSITION);
bMenuEnabled = FALSE;
EnableMenuItem(hPopupMenu, ID_DELETE, MF_DISABLED | MF_GRAYED);
DrawMenuBar(hWnd);
}
return 0;
}
}
break;
}
case WM_DESTROY:
{
// Destroy the popup menu
DestroyMenu(hPopupMenu);
PostQuitMessage(0);
return 0;
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
```
阅读全文