好友
阅读权限40
听众
最后登录1970-1-1
|
一个简单的弹出菜单的创建
链接:http://www.iawen.com/read.php/204.htm
好久没弄了,只是实验一下,呵呵!
所涉及的API,就是一个TrackPopupMenu或者TrackPopupMenuEx!
原型如下:
BOOL TrackPopupMenu(
HMENU hMenu, //指向弹出菜单的句柄
UINT uFlags, //设置的标志位,用于指示弹出菜单的样式,如文字对齐方式
int x,
int y, //弹出菜单的左上角位置
int nReserved,
HWND hWnd, //接收弹出菜单消息的窗口
HWND prcRect //忽略
);[separator]
及
BOOL TrackPopupMenuEx( HMENU hmenu,
UINT fuFlags,
int x,
int y,
HWND hwnd,
LPTPMPARAMS lptpm
);
首先在资源里添加好一个菜单资源,如下:IDR_POPMENU MENU
BEGIN
POPUP "1"
BEGIN
MENUITEM "弹出消息一", ID_SUB_ONE
MENUITEM "弹出消息二", ID_SUB_TWO
MENUITEM SEPARATOR
MENUITEM "退出", ID_SUB_EXIT
END
END
由于是在响应右键点击时弹出菜单的,所以在消息响应里处理WM_RBUTTOMDOWN消息时弹出菜单:
1、首先是获取一个菜单句柄
[codes]
HMENU hMenu=LoadMenu(g_hInst,MAKEINTRESOURCE(IDR_POPMENU));
HMENU hSubMenu=GetSubMenu(hMenu,0);
[/codes]
2、其次是获取弹出菜单的左上角位置,这里是通过获取光标的位置来设置的:
[codes]
POINT pos;
GetCursorPos(&pos);
[/codes]
3、接下来就是弹出菜单了,直接调用API:
TrackPopupMenu(hSubMenu,TPM_LEFTBUTTON,pos.x,pos.y,0,hDlg,NULL);
4、然后在WM_COMMAND消息里响应菜单消息,而这里wParam的高位16为0,低位16位对应的则是消息ID:
[codes=c]
case WM_COMMAND:
if(HIWORD(wParam)==0){
switch(LOWORD(wParam)){
case ID_SUB_ONE:
MessageBox(hDlg,TEXT("对应菜单按钮一"),TEXT("Test"),0);
return TRUE;
case ID_SUB_TWO:
MessageBox(hDlg,TEXT("对应菜单按钮二"),TEXT("Test"),0);
return TRUE;
case ID_SUB_EXIT:
EndDialog(hDlg,0);
return TRUE;
}
}
[/codes]
测试运行如下:
完整和代码如下:
[codes=c]
#include<windows.h>
#include"resource.h"
HINSTANCE g_hInst;
INT_PTR CALLBACK MainDlgProc(HWND,UINT,WPARAM,LPARAM);
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE,LPSTR lpCmdLine,int nShowCmd)
{
g_hInst=hInstance;
DialogBox(hInstance,MAKEINTRESOURCE(IDD_DIALOG1),NULL,MainDlgProc);
return 0;
}
INT_PTR CALLBACK MainDlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
switch(uMsg){
case WM_INITDIALOG:
{
HICON hIcon=LoadIcon(g_hInst,MAKEINTRESOURCE(IDI_MAIN));
SendMessage(hDlg,WM_SETICON,ICON_BIG,(LPARAM)hIcon);
SendMessage(hDlg,WM_SETICON,ICON_SMALL,(LPARAM)hIcon);
SetWindowText(hDlg,TEXT("Test Popup Memu"));
SetDlgItemText(hDlg,IDC_INFO,TEXT("Write By Iawen --2009.02.04"));
return TRUE;
}
case WM_SYSCOMMAND:
switch(wParam)
{
case SC_CLOSE:
DestroyWindow(hDlg);
PostQuitMessage(0);
return TRUE;
case SC_MINIMIZE:
return TRUE;
}
case WM_RBUTTONDOWN:
{
HMENU hMenu=LoadMenu(g_hInst,MAKEINTRESOURCE(IDR_POPMENU));
HMENU hSubMenu=GetSubMenu(hMenu,0);
POINT pos;
GetCursorPos(&pos);
TrackPopupMenu(hSubMenu,TPM_LEFTBUTTON,pos.x,pos.y,0,hDlg,NULL);
}
return TRUE;
case WM_COMMAND:
if(HIWORD(wParam)==0){
switch(LOWORD(wParam)){
case ID_SUB_ONE:
MessageBox(hDlg,TEXT("对应菜单按钮一"),TEXT("Test"),0);
return TRUE;
case ID_SUB_TWO:
MessageBox(hDlg,TEXT("对应菜单按钮二"),TEXT("Test"),0);
return TRUE;
case ID_SUB_EXIT:
EndDialog(hDlg,0);
return TRUE;
}
}
}
return FALSE;
}
[/codes] |
免费评分
-
查看全部评分
|