在玩一些小游戏时,我们总会发现许多的按钮可以点击。在easyx中可以制作出类似的简单的按钮。那么该如何去制作呢?
实现该功能主要由几个部分组成。
一.消息结构体的定义
ExMessage msg = { 0 };
ExMessage是一个特定的结构体类型。以下是其中包含了的元素,但是许多的元素很少用到,只需了解小部分即可。
struct ExMessage
{
USHORT message; // The message identifier
union
{
// Data of the mouse message
struct
{
bool ctrl :1; // Indicates whether the CTRL key is pressed
bool shift :1; // Indicates whether the SHIFT key is pressed
bool lbutton :1; // Indicates whether the left mouse button is pressed
bool mbutton :1; // Indicates whether the middle mouse button is pressed
bool rbutton :1; // Indicates whether the right mouse button is pressed
short x; // The x-coordinate of the cursor
short y; // The y-coordinate of the cursor
short wheel; // The distance the wheel is rotated, expressed in multiples or divisions of 120
};
// Data of the key message
struct
{
BYTE vkcode; // The virtual-key code of the key
BYTE scancode; // The scan code of the key. The value depends on the OEM
bool extended :1; // Indicates whether the key is an extended key, such as a function key or a key on the numeric keypad. The value is true if the key is an extended key; otherwise, it is false.
bool prevdown :1; // Indicates whether the key is previously up or down
};
// Data of the char message
TCHAR ch;
// Data of the window message
struct
{
WPARAM wParam;
LPARAM lParam;
};
};
};
二.判断函数
bool inarea(int mx, int my, int x, int y, int w, int h)
{
if (mx > x && mx<x+w && my>y && my <y+h) {
return true;
}
return false;
}
该函数主要就是判断鼠标是否在按钮的区域内。
三.绘制按钮函数
bool button(int x, int y, int w, int h, const char* str)
{
if (inarea(msg.x, msg.y, x, y, w, h)) {
setfillcolor(RED);
}
else {
setfillcolor(RGB(128, 11, 35));
}
fillrectangle(x, y, x+w, y+h);//绘制矩形
int cx, cy;//使文字居中
cx = (w - textwidth(str)) / 2;
cy = (h - textheight(str)) / 2;
settextcolor(BLACK);
outtextxy(x+cx, y+cy, str);
if (msg.message == WM_LBUTTONDOWN && inarea(msg.x, msg.y, x, y, w, h)) {
return true;
}
return false;
}
该函数实现了一个矩形按钮的绘制,并且实现了按钮内文字的居中显示,及使用按钮时的虚实变化。
四.主函数
int main()
{
initgraph(1000, 600, EX_SHOWCONSOLE);//创建图形窗口
setbkcolor(RGB(237, 143, 9));//调节背景颜色
setbkmode(TRANSPARENT);//设置背景的模式
cleardevice();//清屏函数
while (true)
{
peekmessage(&msg,EX_MOUSE)//获取鼠标信息
BeginBatchDraw();//双缓冲绘图,解决闪图的情况
if (button(20, 20, 150, 35, "start game")) {
printf("start\n");
}
EndBatchDraw();
msg.message = 0;
}
getchar();
return 0;
}
通过以上的步骤,就可以绘制一个简单的按钮啦!