vs封装多个按钮的代码是什么
时间: 2023-03-26 08:03:54 浏览: 55
您好,以下是封装多个按钮的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#define MAX_BUTTONS 10
typedef struct {
char* text;
int x, y, width, height;
void (*onClick)();
} Button;
Button buttons[MAX_BUTTONS];
int numButtons = ;
void addButton(char* text, int x, int y, int width, int height, void (*onClick)()) {
if (numButtons >= MAX_BUTTONS) {
printf("Error: too many buttons\n");
exit(1);
}
buttons[numButtons].text = text;
buttons[numButtons].x = x;
buttons[numButtons].y = y;
buttons[numButtons].width = width;
buttons[numButtons].height = height;
buttons[numButtons].onClick = onClick;
numButtons++;
}
void drawButton(Button* button, HDC hdc) {
RECT rect = { button->x, button->y, button->x + button->width, button->y + button->height };
DrawText(hdc, button->text, strlen(button->text), &rect, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
}
void drawButtons(HDC hdc) {
for (int i = ; i < numButtons; i++) {
drawButton(&buttons[i], hdc);
}
}
void handleMouseClick(int x, int y) {
for (int i = ; i < numButtons; i++) {
if (x >= buttons[i].x && x <= buttons[i].x + buttons[i].width &&
y >= buttons[i].y && y <= buttons[i].y + buttons[i].height) {
buttons[i].onClick();
break;
}
}
}
void onClickButton1() {
printf("Button 1 clicked\n");
}
void onClickButton2() {
printf("Button 2 clicked\n");
}
int main() {
addButton("Button 1", 100, 100, 100, 50, onClickButton1);
addButton("Button 2", 100, 200, 100, 50, onClickButton2);
HWND hwnd = GetConsoleWindow();
HDC hdc = GetDC(hwnd);
drawButtons(hdc);
MSG msg;
while (GetMessage(&msg, NULL, , )) {
if (msg.message == WM_LBUTTONDOWN) {
int x = LOWORD(msg.lParam);
int y = HIWORD(msg.lParam);
handleMouseClick(x, y);
}
}
ReleaseDC(hwnd, hdc);
return ;
}