C++如何获得鼠标在控制台中的字符坐标或使用中的应用程序字符坐标
效果
获取鼠标的以字符为单位的坐标,原点为当前操作的窗口,可以不是原(显示坐标的)程序窗口,也可以是桌面
所需头文件
windows.h
#include<windows.h>
#include<iostream>
using namespace std;
int main() {
POINT p;
int x,y;
for(;;){
system("cls");
CONSOLE_FONT_INFO a;
GetCursorPos(&p);
ScreenToClient(GetForegroundWindow(),&p);
GetCurrentConsoleFont(GetStdHandle(STD_OUTPUT_HANDLE),FALSE,&a);
x=p.x/a.dwFontSize.X;
y=p.y/a.dwFontSize.Y;
cout << x << " " << y;
Sleep(100);
}
}
其中
GetCursorPos()函数获取光标坐标
ScreenToClient(GetForegroundWindow(),&p);获取在使用窗口中的坐标(以像素为单位)
GetCurrentConsoleFont(GetStdHandle(STD_OUTPUT_HANDLE),FALSE,&a);获取控制台的字体大小(一个字符的高度和宽度)
信息都在变量结构体中
以此为基础,可以做一个小游戏
#include<iostream>
#include<stdlib.h>
#include<ctime>
#include<Windows.h>
#define key(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0)
using namespace std;
int a[20][20];
POINT p;
int coin=0,n,m,x,y;
void watch();
int main(){
int l=0;
srand((int)time(0));
system("pause");
system("cls");
for(;;){
if(l==0){
n=rand() % 20;
m=rand() % 20;
a[n][m]=1;
l=1;
}
watch();
for(int q=0;q<=0;q--){
Sleep(10);
if(key(VK_LBUTTON)){
CONSOLE_FONT_INFO k;
GetCursorPos(&p);
ScreenToClient(GetForegroundWindow(),&p);
GetCurrentConsoleFont(GetStdHandle(STD_OUTPUT_HANDLE),FALSE,&k);
x=p.x/k.dwFontSize.X;
y=p.y/k.dwFontSize.Y;
if(m==x&&n==y){
l=0;
coin++;
q=10;
a[n][m]=0;
}
}
}
system("cls");
}
}
void watch(){
for(int i=0;i<20;i++){
for(int j=0;j<20;j++){
if(a[i][j]==0){
cout << " ";
}
if(a[i][j]==1){
cout << "#";
}
}
cout << "█" << endl;
}
cout << "███████████" << endl;
cout << coin << endl;
}