c++实现easyx封装按钮
时间: 2023-09-23 18:03:45 浏览: 174
要实现easyx封装按钮,可以先创建一个Button类,包含按钮的属性和方法。以下是一个简单的示例:
```c++
#include <graphics.h>
class Button {
private:
int x, y; // 按钮左上角坐标
int width, height; // 按钮宽度和高度
COLORREF color; // 按钮颜色
char* text; // 按钮文字
public:
Button(int _x, int _y, int _width, int _height, COLORREF _color, char* _text) : x(_x), y(_y), width(_width), height(_height), color(_color), text(_text) {}
void draw() { // 绘制按钮
setfillcolor(color);
solidrectangle(x, y, x + width, y + height);
setbkmode(TRANSPARENT); // 文字背景透明
settextcolor(WHITE);
settextstyle(20, 0, _T("微软雅黑"));
outtextxy(x + width / 2 - textwidth(text) / 2, y + height / 2 - textheight(text) / 2, text);
}
bool isClicked(int mx, int my) { // 检查是否被点击
if (mx >= x && mx <= x + width && my >= y && my <= y + height) {
return true;
}
return false;
}
};
```
在主函数中,可以创建一个按钮对象并调用其绘制方法:
```c++
int main() {
initgraph(640, 480);
Button btn(100, 100, 100, 50, BLUE, "Click me");
btn.draw();
int mx, my;
while (true) {
if (MouseHit()) {
MOUSEMSG msg = GetMouseMsg();
if (msg.uMsg == WM_LBUTTONDOWN) {
mx = msg.x;
my = msg.y;
if (btn.isClicked(mx, my)) {
// 点击了按钮
break;
}
}
}
}
closegraph();
return 0;
}
```
这样就可以实现一个简单的easyx封装按钮了。