加速键的使用

加速键的使用


 添加加速键
 
 加载加速键表
  HACCEL WINAPI LoadAccelerators(
  _In_opt_ HINSTANCE hInstance,
  _In_     LPCTSTR   lpTableName   // MAKEINTRESOURCE(加速键表ID);
);


翻译加速键
   在GetMessage的循环内,放在TranslateMessage的前面.
  int WINAPI TranslateAccelerator(
  _In_ HWND   hWnd,
  _In_ HACCEL hAccTable,
  _In_ LPMSG  lpMsg
);
该函数失败返回0,成功返回非0.


TranslateAccelerator(hWnd,&nMsg)
{
   if(nMsg.message != WM_KEYDOWN)
   return 0;
   根据nMsg.wParam的虚拟键码值,可以获取那些按键被按下.
   拿着CTRL+Q到加速键表中去匹配查找.
   if(没有找到)
   return 0;
   
   然后填充数据
     将wParam 的高字填充为1,低字填充为加速键ID,
SendMessage(hwnd,WM_COMMAND,wParam,lParam);
   
}


#include
#include "resource.h"
// 窗口处理函数
HINSTANCE g_hInstance = 0;
HWND g_hWnd = 0;
LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_COMMAND:
switch (LOWORD(wParam))
{
case ID_NEW:
MessageBox(NULL, L"NEW", L"infor", MB_OK);
break;
case ID_QUIT:
MessageBox(NULL, L"QUIT", L"infor", MB_OK);
break;
case ID_ABOUT:
MessageBox(NULL, L"ABOUT", L"infor", MB_OK);
break;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
default:
break;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
// 窗口注册函数
void Register(LPCWSTR lpClassName, WNDPROC wndproc)
{
WNDCLASSEX wcx = { 0 };


wcx.cbClsExtra = 0;
wcx.cbSize = sizeof(wcx);
wcx.cbWndExtra = 0;
wcx.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcx.hCursor = LoadCursor(g_hInstance, IDC_ARROW);
wcx.hIcon = NULL;
wcx.hIconSm = NULL;
wcx.hInstance = g_hInstance;
wcx.lpfnWndProc = wndproc;
wcx.lpszClassName = lpClassName;
wcx.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1);
wcx.style = CS_HREDRAW | CS_VREDRAW;


RegisterClassEx(&wcx);
}


HWND CreateMain(LPCWSTR lpClassName)
{
g_hWnd= CreateWindowEx(0, lpClassName, L"LEARN", WS_OVERLAPPEDWINDOW, 100, 100, 700, 500, NULL, NULL, g_hInstance, NULL);
ShowWindow(g_hWnd, SW_SHOW);
UpdateWindow(g_hWnd);
return g_hWnd;
}


int exec()
{
HACCEL  hac = LoadAccelerators(g_hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1));
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
TranslateAccelerator(g_hWnd, hac, &msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
g_hInstance = hInstance;
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
TCHAR szAppName[] = L"MAIN";
Register(szAppName, WndProc);
CreateMain(szAppName);
return exec();

}

你可能感兴趣的:(PC桌面应用)