C++鼠标操作(按钮)

直接放代码

这个东西可以在C++黑窗口上弄鼠标操作的按钮。
当然,仔细研究一下就能拿鼠标做很多事情。

#include<cmath>
#include<ctime>
#include<cstdio>
#include<cstdlib>
#include<windows.h>
#include<algorithm>
using namespace std;

#define KEY_DOWN(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0)
//不要问我这是什么

struct Button{//按钮类型
    int x,y,color;//按钮位置和颜色
    const char *name;//名字
    int len;//名字的长度
};

void GetPos(POINT &pt){//获得鼠标相对于屏幕的位置
//POINT是自带类型
    HWND hwnd=GetForegroundWindow();
    GetCursorPos(&pt);
    ScreenToClient(hwnd,&pt);
    pt.y=pt.y/16,pt.x=pt.x/16;//除以16,想不明白自己把它去掉试试
}

void color(int a){SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);}
//修改颜色
//想知道每个颜色的代码就for循环1到256看看
void gto(int x,int y)//将打字的光标移到x行y列
{
    COORD pos;pos.X=y*2;pos.Y=x;
    //必须反过来
    //y*2是因为汉字是2个字符
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
}

Button NewButton(int x,int y,int color,const char *name){
    Button t;
    t.x=x,t.y=y,t.name=name;
    t.color=color;
    t.len=strlen(name);
    return t;//新建按钮,返回它
}

bool Preserve(Button A){
    //维护一个按钮
    //如果要使这个起作用必须在循环中不断执行它
    //详见后面的示例
    gto(A.x,A.y),color(A.color),printf("%s",A.name);
    POINT pt;
    GetPos(pt);
    if(pt.y==A.x&&(pt.x>=A.y&&pt.x<=A.y+A.len/2)){
        color(A.color+16),gto(A.x,A.y),printf("%s",A.name);
        if(KEY_DOWN(MOUSE_MOVED)) return 1;//检测到点击按钮
    }
    return 0;//没有检测到
}

//没有main()?!
//将这个东西保存在编译器的头文件库中,自己取个名字(如cursor.h)
//在其他程序中可以#include<cursor.h>,当然要保证用的是保存过这个的编译器
//然后就可以照常使用这里面的任何东西

示例

#include<cursor.h>

int main(){
    Button A=NewButton(10,10,7,"这是一个普通的按钮");
    while(1){
        if(Preserve(A))
            gto(9,10),color(7),printf("你在点击这个按钮");
        else
            gto(9,10),color(7),printf("                ");//清除"你在点击这个按钮"的痕迹
        Sleep(100);//不写这个会很闪
    }
}
  • 26
    点赞
  • 119
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值