关于HOOK的一个小问题

C++在使用HOOK的时候遇到了一些小问题。

SetWindowsHookEx(WH_KEYBOARD_LL,KeyboardProc,GetModuleHandle(_T("WillSetHook")), 0 );

设置没问题 都成功了。

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
//KeyboardHookStruct KHS = new KeyboardHookStruct();
//KHS = (KeyboardHookStruct)lParam;
if (WM_KEYDOWN == wParam /
&& (KHS.flags & 128)/64 == 0*/)
{
keybd_event(66,0,0,0);
keybd_event(66,0,KEYEVENTF_KEYUP,0);
return 1;
}

return CallNextHookEx(NULL, nCode, wParam, lParam);

}
这个是我的钩子函数,也能正确调用,没问题。问题就出在这个LPARAM这个参数上。因为我用的是WH_KEYBOARD_LL钩子,所以LPARAM这个参数是一个KeyboardHookStruct类型的结构体(或者是类),但是这个结构体要怎么定义呢?,或者需要包含什么头文件呢?

我自己尝试定义了这个结构体(类):
// public class KeyboardHookStruct
// {
// public int vkCode;

// public int scanCode;

// public int flags;
// public int time;

// public int dwExtraInfo;
// };
// struct class KeyboardHookStruct
// {
// int vkCode;

// int scanCode;

// int flags;
// int time;

// int dwExtraInfo;
// };
类型和网上给出的类型是一样的,但是却无法编译过,可能是我基础不太扎实。
求助大神教我改怎么去定义这个结构体,在哪里定义(我自定义的类内还是类外?),具体的定义方法,我的钩子函数里 该怎么去写,才能将LPARAM里面的值拿出来用。

(被注释掉的代码因编译错误而被注释掉了)

3个回答

KBDLLHOOKSTRUCT
The KBDLLHOOKSTRUCT structure contains information about a low-level keyboard input event.

typedef struct tagKBDLLHOOKSTRUCT {
DWORD vkCode; // virtual key code
DWORD scanCode; // scan code
DWORD flags; // flags
DWORD time; // time stamp for this message
DWORD dwExtraInfo; // extra info from the driver or keybd_event
} KBDLLHOOKSTRUCT, FAR *LPKBDLLHOOKSTRUCT, *PKBDLLHOOKSTRUCT;

Members
vkCode
Specifies a virtual-key code. The code must be a value in the range 1 to 254.
scanCode
Specifies a hardware scan code for the key.
flags
Specifies the extended-key flag, event-injected flag, context code, and transition-state flag. Value Description
0 Specifies whether the key is an extended key, such as a function key or a key on the numeric keypad. The value is 1 if the key is an extended key; otherwise, it is 0.
1-3 Reserved.
4 Specifies whether the event was injected. The value is 1 if the event was injected; otherwise, it is 0.
5 Specifies the context code. The value is 1 if the ALT key is pressed; otherwise, it is 0.
6 Reserved.
7 Specifies the transition state. The value is 0 if the key is pressed and 1 if it is being released.

An application can use the following values to test the keystroke flags: Value Purpose
LLKHF_EXTENDED Test the extended-key flag.

LLKHF_INJECTED Test the event-injected flag.

LLKHF_ALTDOWN Test the context code.

LLKHF_UP Test the transition-state flag.

time
Specifies the time stamp for this message.
dwExtraInfo
Specifies extra information associated with the message.

Declared in winuser.h.

zhao4zhong1
赵4老师 回复a7716021: Yes,ofcourse,why not,certainly!
3 年多之前 回复
a7716021
a7716021 是不是说我引入一个winuser.h头文件 就可以直接使用该结构体了?
3 年多之前 回复

查MSDN是Windows程序员必须掌握的技能之一。

只要引用winuser.h头文件就可以直接用这个结构体。
然后强转LPARAM参数就可以为自己所用。就这么简单。
我的基础真是太烂了。
问题解决,谢谢赵4老师 哈哈。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问