电脑的控制离不开鼠标和键盘。今天闲着没事,写一个后台监视鼠标动作的代码。
首先,我们先认识几个函数:
GetCursorPos():鼠标位置检测函数。用法:
POINT p;
int x,y;//定义变量
while(1){
GetCursorPos(&p);//将鼠标所在位置存在p中
//x=鼠标x轴
//y=鼠标y轴
}
KEY_DOWN():检测鼠标按键,按下返回true,为按下返回false
KEY_DOWN(VK_LBUTTON) | 检测鼠标左键 |
KEY_DOWN(MOUSE_EVENT) | 检测鼠标右键 |
KEY_DOWN(MOUSE_WHEELED) | 检测鼠标滚轮键(非滚轮) |
时间获取函数:
time_t t=time(0);
char tmp[64];
strftime(tmp,sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z",localtime(&t));
puts(tmp);
即可输出中国标准时间。
看完了函数,上代码:
#include<bits/stdc++.h>
#include<windows.h>
#define KEY_DOWN(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0)
using namespace std;
POINT p;
int x,y;
int main(){
ShowWindow(GetForegroundWindow(),0);
freopen("鼠标移动记录.txt","w",stdout);//打开文件输出流
while(1){
GetCursorPos(&p);
if(p.x!=x||p.y!=y){
time_t t=time(0);
char tmp[64];
strftime(tmp,sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z",localtime(&t));
puts(tmp);
cout<<"鼠标由"<<x<<" "<<y<<"移动至"<<p.x<<" "<<p.y<<endl;
x=p.x;
y=p.y;
}
if(KEY_DOWN(VK_LBUTTON)){
time_t t=time(0);
char tmp[64];
strftime(tmp,sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z",localtime(&t));
puts(tmp);
cout<<"鼠标在"<<p.x<<" "<<p.y<<"左击"<<"\n";
}
if(KEY_DOWN(MOUSE_EVENT)){
time_t t=time(0);
char tmp[64];
strftime(tmp,sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z",localtime(&t));
puts(tmp);
cout<<"鼠标在"<<p.x<<" "<<p.y<<"右击"<<"\n";
}
if(KEY_DOWN(MOUSE_WHEELED)){
time_t t=time(0);
char tmp[64];
strftime(tmp,sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z",localtime(&t));
puts(tmp);
cout<<"鼠标在"<<p.x<<" "<<p.y<<"按下滚轮"<<"\n";
}
Sleep(100);
}
return 0;
}
但是用起来总会出现许多没必要的鼠标移动记录,所以我又写了一个只记录左右击、按下滚轮的代码:
#include<bits/stdc++.h>
#include<windows.h>
#define KEY_DOWN(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0)
using namespace std;
POINT p;
int x,y;
int main(){
ShowWindow(GetForegroundWindow(),0);
freopen("记录.txt","w",stdout);
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
GetConsoleMode(hStdin, &mode);
mode &= ~ENABLE_QUICK_EDIT_MODE;
SetConsoleMode(hStdin, mode);
while(1){
GetCursorPos(&p);
if(KEY_DOWN(VK_LBUTTON)){
time_t t=time(0);
char tmp[64];
strftime(tmp,sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z",localtime(&t));
puts(tmp);
cout<<"鼠标在"<<p.x<<" "<<p.y<<"左击"<<endl;
}
if(KEY_DOWN(MOUSE_EVENT)){
time_t t=time(0);
char tmp[64];
strftime(tmp,sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z",localtime(&t));
puts(tmp);
cout<<"鼠标在"<<p.x<<" "<<p.y<<"右击"<<endl;
}
if(KEY_DOWN(MOUSE_WHEELED)){
time_t t=time(0);
char tmp[64];
strftime(tmp,sizeof(tmp), "%Y/%m/%d %X %A 本年第%j天 %z",localtime(&t));
puts(tmp);
cout<<"鼠标在"<<p.x<<" "<<p.y<<"按下滚轮"<<endl;
}
Sleep(100);
}
return 0;
}
本篇文章就到这里,欢迎大家留言指点。