今天用小熊猫c++写了一个“画图”,一开始是没有问题的,但后来上kbhit()选择颜色和字体就有问题了,必须按住键盘才能画, 大 佬 帮忙看一下,谢谢。
鼠标左键画图,右键橡皮擦
源代码:
#include
#include<math.h>
#include<windows.h>
#include<bits/stdc++.h>
#include<graphics.h>
using namespace std;
int x,y,ans=0;
bool flag1=false,flag2=false;
int main()
{
initgraph(1000,3000);
setbkcolor(WHITE);
setcolor(BLACK);
ege_enable_aa(true);
for(;is_run();delay_fps(60)) {
while(mousemsg()){
if(kbhit()) {
if(getch()==99) cleardevice();
if(getch()==66) setcolor(BLACK);
if(getch()==112) setcolor(PINK);
if(getch()==114) setcolor(RED);
if(getch()==121) setcolor(YELLOW);
if(getch()==98) setcolor(BLUE);
if(getch()==103) setcolor(GREEN);
if(getch()==71) setcolor(GRAY);
if(getch()==49) setlinewidth(1);
if(getch()==50) setlinewidth(2);
if(getch()==51) setlinewidth(3);
if(getch()==52) setlinewidth(4);
if(getch()==53) setlinewidth(5);
if(getch()==54) setlinewidth(6);
if(getch()==55) setlinewidth(7);
if(getch()==56) setlinewidth(8);
if(getch()==57) setlinewidth(9);
}//出问题的地方
mouse_msg msg=getmouse();
if(msg.is_left()&&msg.is_down()) {
x=msg.x;
y=msg.y;
flag1=true;
}
if(msg.is_right()&&msg.is_down()) {
flag2=true;
}
if(msg.is_left()&&msg.is_up()) {
flag1=false;
}
if(msg.is_right()&&msg.is_up()) {
flag2=false;
}
if(flag1) {
ege_line(x,y,msg.x,msg.y);
x=msg.x;
y=msg.y;
}
if(flag2) {
setfillcolor(WHITE);
ege_fillellipse(msg.x-20,msg.y-20,40,40);
}
}
}
}
谁知道为什么呀
你应该像下面我的代码那样调用getch并将按键编码保存到一个变量k中,然后再if(k==...)判断k的值;而不应该在每个if (getch()==...)判断中调用getch
#include <conio.h>
#include <windows.h>
int main() {
int k;
while (1) {
if (kbhit()) {
k=getch();
if (0==k || 0xE0==k) k=k<<8|getch();
if (27==k) break;//按Esc键退出
cprintf("\r\n%04X\r\n",k);
}
Sleep(200);
cprintf(".");
}
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话: