Windows API Primer   アクセラレータ

ホーム   目次

アクセラレータ

アクセラレータキーは、修飾キーと文字や数字のキーの組み合わせを押すことで、メニュー項目を選択したことになるキーの組み合わせです。

accelerator.c


#include <windows.h>

#define FILE 10
#define SAVE 13
#define QUIT 14
#define HELP 30
#define ABOU 31

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int     WINAPI   WinMain(HINSTANCE hInstance,
			 HINSTANCE hPrevInstance,
			 LPSTR     lpCmdLine,
			 int       nCmdShow)
{
  HMENU    hMenubar;
  HMENU    hMenuFile;
  HMENU    hMenuHelp;
  
  WNDCLASS wc;
  HWND     hwnd;
  MSG      msg;
  
  HACCEL   haccel;
  ACCEL    accel[3];

  hMenubar  = CreateMenu();
  hMenuFile = CreateMenu();
  hMenuHelp = CreateMenu();

  AppendMenu(hMenuFile, MF_STRING, SAVE, TEXT("Save Ctrl + S"));
  AppendMenu(hMenuFile, MF_SEPARATOR, 0, NULL        );
  AppendMenu(hMenuFile, MF_STRING, QUIT, TEXT("Quit Ctrl + Q"));
  AppendMenu(hMenubar , MF_POPUP , (UINT_PTR)hMenuFile, TEXT("File"));
  AppendMenu(hMenuHelp, MF_STRING, ABOU, TEXT("About Ctrl + A"));
  AppendMenu(hMenubar , MF_POPUP , (UINT_PTR)hMenuHelp, TEXT("Help"));

  wc.style         = CS_HREDRAW | CS_VREDRAW;
  wc.lpfnWndProc   = WndProc;
  wc.cbClsExtra    = 0;
  wc.cbWndExtra    = 0;
  wc.hInstance     = hInstance;
  wc.hIcon         = NULL;
  wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
  wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND + 1;
  wc.lpszMenuName  = NULL;
  wc.lpszClassName = TEXT("ACCELERATOR");

  RegisterClass(&wc);

  hwnd            = CreateWindow(TEXT("ACCELERATOR"),
				 TEXT("Windows API Primer"),
				 WS_OVERLAPPEDWINDOW | WS_VISIBLE,
				 CW_USEDEFAULT, CW_USEDEFAULT, 300, 200,
				 NULL, hMenubar, hInstance, NULL);

  accel[0].key   = 0x53; // S key
  accel[0].cmd   = SAVE;
  accel[0].fVirt = FCONTROL | FVIRTKEY;

  accel[1].key   = 0x51; // Q key
  accel[1].cmd   = QUIT;
  accel[1].fVirt = FCONTROL | FVIRTKEY;

  accel[2].key   = 0x41; // A key
  accel[2].cmd   = ABOU;
  accel[2].fVirt = FCONTROL | FVIRTKEY;

  haccel = CreateAcceleratorTable(accel, 3);
  
  while (GetMessage(&msg, NULL, 0, 0))
    {
      if (!TranslateAccelerator(hwnd, haccel, &msg)) {
	DispatchMessage(&msg);
      }
    }

  DestroyAcceleratorTable(haccel);
  
  return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
  switch (msg)
    {
    case WM_COMMAND:
      switch LOWORD(wParam)
	{
	case SAVE:
	  MessageBox(hwnd, TEXT("Saved."), TEXT("OK"), MB_OK);
	  break;
	case QUIT:
	  SendMessage(hwnd, WM_CLOSE, 0, 0);
	  break;
	case ABOU:
	  MessageBox(hwnd, TEXT("Accelerator Ver. 1.0"), TEXT("About"), MB_OK);
	  break;
	}
      break;
    case WM_DESTROY:
      PostQuitMessage(0);
      break;
    }
  return DefWindowProc(hwnd, msg, wParam, lParam);
}
    

実行結果


Control + S で OK メッセージボックスが現れ、Control + A で About メッセージボックスが現れます。Control + Q でアプリケーションが終了します。



4083 visits
Posted: Jun. 05, 2020
Update: Jun. 05, 2020

ホーム   目次