1.鼠标消息函数
鼠标消息需要使用MOUSEMSG类型,比如MOUSEMSG msg;
然后用MoustHit()判断是否有鼠标消息(左键,右键,中间,移动)有鼠标消息返回真,没有返回假
如果有鼠标消息就可以进行接收鼠标消息 msg=GetMouseMsg();
MOUSEMSG是结构体类型 鼠标消息主要成员:
uMsg; //当前鼠标信息
x; //当前鼠标x坐标
y; //当前鼠标y坐标
uMsg可用来判断当前鼠标是什么消息
主要的两个消息1)WM_LBUTTONDOWN鼠标左键消息
2)WM_RBUTTONDOWN鼠标右键消息
#include<stdio.h>
#include<graphics.h>
int main()
{
initgraph(640, 480, SHOWCONSOLE);
setbkcolor(WHITE);//白色
cleardevice();
settextcolor(RED);
//框
fillrectangle(200, 50, 500, 100);
settextcolor(RGB(173, 0, 13));
char arr[] = "按钮";
int width = 300 / 2 - textwidth(arr) / 2;
int height = 50 / 2 - textheight(arr) / 2;
outtextxy(width + 200, height + 50, arr);
//鼠标消息
while (1)
{
if (MouseHit())
{
MOUSEMSG msg = GetMouseMsg();
//printf("鼠标位置坐标(%d,%d\n)", msg.x, msg.y);
switch (msg.uMsg)
{
case WM_LBUTTONDOWN:
将鼠标位置限制在"按钮"框内
if (msg.x > 200 && msg.x < 500 && msg.y>50 && msg.y < 100)
{
printf("测试成功\n");
}
outtextxy(400, 400, "鼠标左键按下");
printf("鼠标位置坐标(%d,%d)\n", msg.x, msg.y);
break;
case WM_RBUTTONDOWN:
outtextxy(400, 400, "鼠标右键按下");
printf("鼠标位置坐标(%d,%d)\n", msg.x, msg.y);
break;
}
}
}
return 0;
}
运行结果
//新版如下
#define _CRT_SECURE_NO_WARNINGS 1//没有显示strcpy不安全
#include <stdio.h>
#include<easyx.h>//包含最新鼠标操作的头文件
void button(int x,int y,int w,int h,const char*text)//w是宽度y是高度
{
setbkmode(TRANSPARENT);//文字背景透明
setfillcolor(BROWN);
//绘制一个圆角矩形
fillroundrect(x,y,x+w,y+h,10,10);
settextstyle(30, 0, "黑体");
//让文字居中
char text_[50] = "button";
strcpy(text_, text);
int tx = x + (w - textwidth(text)) / 2;
int ty = y + (h - textheight(text)) / 2;
outtextxy(tx, ty, text);
}
int main()
{
//新的版本加了EW_前缀
initgraph(640, 480, EW_SHOWCONSOLE);
button(50, 50, 150, 50,"按钮");
//宽度150高度50
ExMessage msg;//MOUSEMSG的替代
while (true)
{
if (peekmessage(&msg, EM_MOUSE))//EM_MOUSE为获取鼠标消息,有鼠标消息返回真没有返回假
{
switch (msg.message)
{
case WM_LBUTTONDOWN:
if (msg.x >= 50 && msg.x <= 50 + 150 && msg.y >= 50 && msg.y <= 50 + 50)
{
printf("测试成功\n");
}
}
}
}
getchar();
//关闭窗口
closegraph();
return 0;
}
运行结果
//注意几点
void fillroundrect(
int left,
int top,
int right,
int bottom,
int ellipsewidth,
int ellipseheight
);