控件–Hotkey-WindowsAPI论坛-WindowsAPI-津桥芝士平台

控件–Hotkey

使用WindowsAPI,创建Hotkey控件:

#include <windows.h>
#include <commctrl.h>
#pragma comment(lib, "comctl32.lib")
#pragma comment(linker,"\"/manifestdependency:type='win32' \
name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \
processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")

#define ID_HOTKEY 101

LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
    switch (message) {
    case WM_CREATE: {
        // Ensure that the common control DLL is loaded. 
        INITCOMMONCONTROLSEX icex;  //declare an INITCOMMONCONTROLSEX Structure
        icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
        icex.dwICC = ICC_HOTKEY_CLASS;   //set dwICC member to ICC_HOTKEY_CLASS    
        // this loads the Hot Key control class.
        InitCommonControlsEx(&icex);
        // 创建热键控件
        HWND hwndHotKey = CreateWindowEx(0, HOTKEY_CLASS, NULL,
            WS_CHILD | WS_VISIBLE | WS_BORDER,
            10, 10, 150, 30,
            hwnd, (HMENU)ID_HOTKEY, NULL, NULL);

        SendMessage(hwndHotKey, HKM_SETHOTKEY, MAKEWORD('H', HOTKEYF_ALT | HOTKEYF_CONTROL), 0);
        if (!RegisterHotKey(hwnd, ID_HOTKEY, MOD_CONTROL | MOD_ALT, 'H')) {
            MessageBox(hwnd, L"Failed to register hotkey!", L"Error", MB_OK);
        }
        break;
    }
    case WM_HOTKEY: {
        // 处理热键事件
        MessageBox(hwnd, L"Hotkey pressed!", L"Notification", MB_OK);
        break;
    }
    case WM_DESTROY:
        UnregisterHotKey(hwnd, ID_HOTKEY);
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hwnd, message, wParam, lParam);
    }
    return 0;
}

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow)
{
    // 创建窗口类
    WNDCLASS wc = {};
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = L"HotKeyExample";
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);

    RegisterClass(&wc);

    // 创建窗口
    HWND hwnd = CreateWindowEx(
        0, L"HotKeyExample", L"HotKey Control Example",
        WS_OVERLAPPEDWINDOW | WS_VISIBLE,
        CW_USEDEFAULT, CW_USEDEFAULT, 300, 200,
        NULL, NULL, hInstance, NULL);

    // 消息循环
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0) > 0) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int)msg.wParam;
}

效果图:

image

 

请登录后发表评论

    没有回复内容