首页 > C++ > DOC界面下调用钩子

DOC界面下调用钩子

2012年6月18日 发表评论 阅读评论

之前想写个很简单的游戏,想用OPENCV,但是不想用MFC,结果写着写着。。发现要响应键盘,显然不能每个While循环都来调用CvWaitKey,最好就是用钩子,但是以前一直是在MFC里用,在DOC界面下没弄过,就要久了大半天,总算搞出来了。。

留做备用,话说代码高亮要怎么弄?

#include "stdafx.h"
#include <windows .h>
#include <stdio .h>
HHOOK g_hMouse;

#define WH_MOUSE_LL 14
typedef struct
{
    POINT pt;
    DWORD mouseData;
    DWORD flags;
    DWORD time;
    ULONG_PTR dwExtraInfo;
} MSLLHOOKSTRUCT, *PMSLLHOOKSTRUCT;

LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode >= 0)
    {
        PMSLLHOOKSTRUCT pmll = (PMSLLHOOKSTRUCT) lParam;

        printf("msg: %lu, x:%ld, y:%ld\n", wParam, pmll->pt.x, pmll->pt.y);
        //TODO...
    }
    return CallNextHookEx(g_hMouse, nCode, wParam, lParam);
}

int main(void)
{
    MSG msg;

    g_hMouse = SetWindowsHookEx( WH_MOUSE_LL, MouseProc, GetModuleHandle(NULL), 0 );
    if (!g_hMouse) printf("Hook error: %d\n", GetLastError());

    while ( GetMessage(&msg, NULL, 0, 0) )
    {
         TranslateMessage(&msg);
         DispatchMessage(&msg);
    }

    UnhookWindowsHookEx(g_hMouse);
    return (int) msg.wParam;
}
#include <windows .h>
#include <stdio .h>
#include <iostream>
using namespace std;
HHOOK g_hMouse = NULL;

//typedef struct tagKBDLLHOOKSTRUCT {
//    DWORD   vkCode;    //按键信息
//    DWORD   scanCode;  //扫描码
//    DWORD   flags;     //0是按下,128是升起
//    DWORD   time;    //扫描时间
//    ULONG_PTR dwExtraInfo;
//} KBDLLHOOKSTRUCT, FAR *LPKBDLLHOOKSTRUCT, *PKBDLLHOOKSTRUCT;
LRESULT CALLBACK KeyBoardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode >= 0)
    {
        PKBDLLHOOKSTRUCT pmll = (PKBDLLHOOKSTRUCT) lParam;

        cout< <int(pmll->vkCode)< <"  "<<int(pmll->scanCode)< <"  "<<int(pmll->flags)< <
            "  "<<int(pmll->time)< <endl;
    }
    return CallNextHookEx(g_hMouse, nCode, wParam, lParam);
}

int main(void)
{
    MSG msg;

    g_hMouse = SetWindowsHookEx( WH_KEYBOARD_LL, KeyBoardProc, GetModuleHandle(NULL), 0 );
    if (!g_hMouse) printf("Hook error: %d\n", GetLastError());

    while ( GetMessage(&msg, NULL, 0, 0) )
    {
        //TranslateMessage(&msg);
        //DispatchMessage(&msg);
    }

    UnhookWindowsHookEx(g_hMouse);
    return (int) msg.wParam;
}

【完】

本文内容遵从CC版权协议,转载请注明出自http://www.kylen314.com

分类: C++ 标签: ,
  1. 本文目前尚无任何评论.
验证码:9 + 4 = ?

友情提示:留言可以使用大部分html标签和属性;

添加代码示例:[code lang="cpp"]your code...[/code]

添加公式请用Latex代码,前后分别添加两个$$