继前篇hook(笔记)_yjx23332的博客-CSDN博客后,我们尝试写一个脚本对全局进行影响。
本文实现鼠标不断按下(位置为鼠标当前位置),3秒后松开,再次按下。
Hook代码
KeyHook.h
#pragma once
#include<windows.h>
#include<stdio.h>
#include <thread>
extern "C" _declspec(dllexport) bool installHook();//安装钩子
extern "C" _declspec(dllexport) bool unInstallHook();//卸载钩子
HHOOK hHook;
LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam);
bool installHook();
bool unInstallHook();
KeyHook.h
#include "KeyHook.h"
static bool flag = false;
HANDLE handle = NULL;
unsigned int CALLBACK Thread(void* args) {
while (flag) {
//鼠标事件,按下,dx,dy,x,y
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
//等待3秒
Sleep(3000);
//松开
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
return 0;
}
LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam) {
HWND hWnd = ::GetActiveWindow();
if (code < 0 || code == HC_NOREMOVE) {
return CallNextHookEx(hHook, code, wParam, lParam);
}
if (lParam & 0x40000000) {
return CallNextHookEx(hHook, code, wParam, lParam);
}
char keyTextBuff[256];
GetKeyNameTextA(lParam, keyTextBuff, 255);
if (keyTextBuff[0] == 'O') {
if (!flag) {
flag = true;
MessageBox(NULL, L"即将开始", L"提示", NULL);
handle = (HANDLE)_beginthreadex(NULL, 0, Thread, NULL, 0, NULL);
}
else {
MessageBox(NULL, L"脚本正在执行", L"提示", NULL);
}
}
else if (keyTextBuff[0] == 'P') {
if (flag){
flag = false;
MessageBox(NULL, L"即将结束", L"提示", NULL);
}
else {
MessageBox(NULL, L"没有执行的脚本", L"提示", NULL);
}
}
return CallNextHookEx(hHook, code, wParam, lParam);;
}
bool installHook() {//安装钩子
//SetWindowsHook只能适用32位,Ex位升级版
hHook = SetWindowsHookEx(
WH_KEYBOARD,//钩子种类,此处我们埋下键盘消息钩子
hookProc,//设置钩子的处理函数,以回调的形式
GetModuleHandle(L"KeyHook"),
NULL//线程ID,NULL自动分配
);
if (hHook == NULL)
return false;
MessageBox(NULL, L"钩子已安装", L"提示", NULL);
return true;
}
bool unInstallHook() {
UnhookWindowsHookEx(hHook);
return true;
}