Win API - 无法向窗口添加弹出菜单和图标
Posted
技术标签:
【中文标题】Win API - 无法向窗口添加弹出菜单和图标【英文标题】:Win API - Unable to add pop up menu and icon to the window 【发布时间】:2014-07-11 08:31:01 【问题描述】:我从http://www.winprog.org/tutorial/ 找到了以下代码来显示菜单和图标,但没有任何反应。只打开一个简单的窗口,没有菜单/图标。我一遍又一遍地检查代码,但找不到缺陷(我是 winAPI 编程的新手)。我正在使用 CodeBlocks 编译器。下面是主文件、资源文件、resource.h的代码。
//menu_one.cpp
#include <windows.h>
#include "resource.h"
const char g_szClassName[] = "myWindowClass";
LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
switch(Message)
case WM_COMMAND:
switch(LOWORD(wParam))
case ID_FILE_EXIT:
PostMessage(hwnd, WM_CLOSE, 0, 0);
break;
case ID_STUFF_GO:
MessageBox(hwnd, "You clicked Go!", "Woo!", MB_OK);
break;
break;
case WM_CLOSE:
DestroyWindow(hwnd);
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;
HWND hwnd;
MSG Msg;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON));
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = MAKEINTRESOURCE(IDR_MYMENU);
wc.lpszClassName = g_szClassName;
wc.hIconSm = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON), IMAGE_ICON, 16, 16, 0);
if(!RegisterClassEx(&wc))
MessageBox(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
hwnd = CreateWindowEx(
WS_EX_CLIENTEDGE,
g_szClassName,
"A Menu",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
NULL, NULL, hInstance, NULL);
if(hwnd == NULL)
MessageBox(NULL, "Window Creation Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
while(GetMessage(&Msg, NULL, 0, 0) > 0)
TranslateMessage(&Msg);
DispatchMessage(&Msg);
return Msg.wParam;
//resource.h
#define IDR_MYMENU 101
#define IDI_MYICON 201
#define ID_FILE_EXIT 9001
#define ID_STUFF_GO 9002
//menu_one.rc
#include "resource.h"
IDR_MYMENU MENU
BEGIN
POPUP "&File"
BEGIN
MENUITEM "E&xit",ID_FILE_EXIT
END
POPUP "&Stuff"
BEGIN
MENUITEM "&Go",ID_STUFF_GO
MENUITEM "Go &Somewhere Else",ID_STUFF_GOSOMEWHEREELSE,0,GRAYED
END
END
IDI_MYICON ICON "menu_one.ico"
【问题讨论】:
顺便说一句,这里不需要GetModuleHandle(NULL)
,你可以使用hInstance
【参考方案1】:
对此最可能的解释是您没有将编译的资源文件 (.res) 传递给链接器。检查项目中的链接器选项,确保将 .res 文件传递给链接器。
【讨论】:
谢谢兄弟...我所做的是文件->新项目->Win 32 GUI(对话框)并复制了代码。代码块处理了其余部分。以上是关于Win API - 无法向窗口添加弹出菜单和图标的主要内容,如果未能解决你的问题,请参考以下文章
各位大神系统Win 10电脑老是弹出Update.exe-无法找到入口,是啥原因,要怎么解决呢?