WinAPI 设定全局热键

text

#include "windows.h"
#include "psapi.h"
#include "assert.h"
#include "cstdio"

static int hk_run, hk_exit;
HWND g_hwnd;

void reg()
{
    hk_run=GlobalAddAtom("C-A-X");
    hk_exit=GlobalAddAtom("C-A-C");

    assert(RegisterHotKey(g_hwnd, hk_run, MOD_CONTROL | MOD_ALT, 'X'));
    assert(RegisterHotKey(g_hwnd, hk_exit, MOD_CONTROL | MOD_ALT, 'C'));
}

void cleanup()
{
    UnregisterHotKey(g_hwnd, hk_run);
    UnregisterHotKey(g_hwnd, hk_exit);
    GlobalDeleteAtom(hk_run);
    GlobalDeleteAtom(hk_exit);
}

void work()
{
    POINT pt;
    HWND hwnd;
    unsigned pid, tid;

    char buf[1024], tmp[1024];

    GetCursorPos(&pt);
    hwnd=WindowFromPoint(pt);
    tid=GetWindowThreadProcessId(hwnd, &pid);

    RECT rect = {pt.x-20, pt.y-20, 40, 40};

    SendMessage(hwnd, WM_GETTEXT, sizeof(buf), (LPARAM)buf);
    MessageBox(0, buf, 0, 0);
    InvalidateRect(hwnd, &rect, true);    
}


LRESULT CALLBACK WndProc(HWND hwnd, unsigned msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        case WM_DESTROY:
            cleanup();
            PostQuitMessage(0);
            return 0;
        case WM_HOTKEY:
            char buf[400];
            if (wParam == hk_run)
                work();
            else if (wParam == hk_exit)
            {
                    MessageBox(0, "Exit...", 0, 0);
                    cleanup();
                    PostQuitMessage(0);
            }
            else
            {
                sprintf(buf, "%d", wParam);
                MessageBox(0, buf, "bad hotkey msg", 0);
            }
            return 0;
            break;
        default: return DefWindowProc(hwnd, msg, wParam, lParam);
    }
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
    MSG msg;
    WNDCLASS wndclass=
    {
        0,
        WndProc,
        0,0,
        hInstance,
        0,0,0,0,
        "hidden",
    };
    assert(RegisterClass(&wndclass));
    g_hwnd=CreateWindow("hidden", "hidden", 0, 0, 0, 0, 0, 0, 0, hInstance, 0);

    reg();

    while (GetMessage(&msg, 0, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}


text

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值