C语言,截取键盘和鼠标消息,无DLL! 50行代码,直接可编译运行
本帖最后由 凌风破浪 于 2015-5-4 11:19 编辑好多年以前写的一段小代码,很简单,是吧
#include <stdio.h>
#include <windows.h>
HHOOK Mouse = 0;
HHOOK KeyBoard = 0;
LRESULT CALLBACK KeyProc( int code, WPARAM w, LPARAM l )
{
//简单打印
printf( "%x\n", code );
printf( ( w == WM_KEYDOWN ) ? "按下%c\n" : "抬起%c\n", ( (PKBDLLHOOKSTRUCT)l )->vkCode );
printf( "%x,%x,%x,%x\n", ( (PKBDLLHOOKSTRUCT)l )->dwExtraInfo, ( (PKBDLLHOOKSTRUCT)l )->flags, ( (PKBDLLHOOKSTRUCT)l )->scanCode, ( (PKBDLLHOOKSTRUCT)l )->time );
return CallNextHookEx( KeyBoard, code, w, l );
}
LRESULT CALLBACK MouseProc( int code, WPARAM w, LPARAM l )
{
//简单打印
if( w == WM_LBUTTONDOWN ) printf( "按下左键\t" );
else if( w == WM_LBUTTONUP ) printf( "抬起左键\t" );
else if( w == WM_RBUTTONDOWN ) printf( "按下右键\t" );
else if( w == WM_RBUTTONUP ) printf( "抬起右键\t" );
else if( w == WM_MOUSEMOVE ) printf( "鼠标移动\t" );
else printf( "未知按键\t" );
printf( "x:%d\ty:%d\n", ( (PMSLLHOOKSTRUCT)l )->pt.x, ( (PMSLLHOOKSTRUCT)l )->pt.y );
return CallNextHookEx( Mouse, code, w, l );
}
int main( void )
{
//注册钩子
KeyBoard = SetWindowsHookEx( WH_KEYBOARD_LL, KeyProc, GetModuleHandle( NULL ), 0 );
Mouse = SetWindowsHookEx( WH_MOUSE_LL, MouseProc, GetModuleHandle( NULL ), 0 );
if( KeyBoard == NULL || Mouse == NULL )
{
printf( "安装钩子出错\n" );
return 0;
};
//以下是WINDOWS循环,用来更新显示的,不用管它
MSG msg;
while( GetMessage( &msg, NULL, 0, 0 ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
};
//注销钩子
UnhookWindowsHookEx( KeyBoard );
UnhookWindowsHookEx( Mouse );
return 0;
};
太秀了 我用 DEV_C++ 运行没有问题,用 VC++6.0 运行,出现 13条错误,我增加了一句 #include "keyhook.h" 后,还有一条错误:fatal error C1083: Cannot open include file: 'keyhook.h': No such file or directory ,不知道怎么处理了
页:
[1]