DP專題
阿新 • • 發佈:2020-07-14
簡介
這是在黑漆漆的程式中,製造使用者可點選的按鈕,來決定程式下一步該作什麼,的基本程式碼。
詳解
標頭檔案
<cstdio>
和<windows.h>
結構體
//這不全別複製
struct Button
{
int x,y,lenx,leny,color1,color0;
char * s;
bool nowpoint;
};
x
和y
是按鈕左上角相對於當前視窗的位置(左右是x,上下是y)
lenx
和leny
按鈕的長與寬(左右是x,上下是y)
color1
和color0
是滑鼠否或是在按鈕上時按鈕的顏色
顏色詳見 這個
s
是輸出的一個串
例如lenx=3,leny=3
的按鈕,是
\[ \begin{matrix}
a b c \\
d e f \\
g h i \\
\end{matrix}
\]
則s
為"abcdefghi"
nowpoint
不用管,使用者用不到。
功能
程式碼 | 功能 |
---|---|
Button a | 新建一個按鈕,預設為"none" |
a.Print(···) | 輸出a |
a.SetButton(···) | 初始化並輸出,返回時為串的長度是(1)否(0)符合規定 |
a.Check(···) | 判斷滑鼠是(1)否(0)點選的a按鈕 |
a.Delete(···) | 刪去a按鈕,加引號的刪除 |
細節
在Check的GetAsyncKeyState中
可選VK_RBUTTON(滑鼠右鍵)或VK_LBUTTON(滑鼠左鍵)
由於win10按左鍵會觸發選擇而不是按左鍵,所以win10推薦用右鍵
程式碼
#include <cstdio>
#include <windows.h>
using namespace std;
const HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
struct Button
{
int x,y,lenx,leny,color1,color0;
char * s;
bool nowpoint;
Button () ;
void Print(bool a=1,int Nowcolor=7);
bool SetButton (int x,int y,int lenx,int leny,int color1,int color0,const char s[],int Nowcolor=7);
bool Check(int Nowcolor=7);
void Delete();
};
Button::Button ()
{
x=y=0;
lenx=4;
leny=1;
color1=7;
color0=0x70;
nowpoint=0;
s=new char [4];
* s=* (s+2)='n';
* (s+1)='o';
* (s+3)='e';
}
void Button::Print(bool a,int Nowcolor)
{
if(a) SetConsoleTextAttribute(handle,this->color1);
else SetConsoleTextAttribute(handle,this->color0);
for(int i=0;i<this->leny;++i)
{
COORD pos = {this->x,this->y+i};
SetConsoleCursorPosition(handle,pos);
for(int j=0;j<this->lenx;++j)
{
printf("%c",*(this->s+i*lenx+j));
}
}
SetConsoleTextAttribute(handle,Nowcolor);
}
bool Button::SetButton (int x,int y,int lenx,int leny,int color1,int color0,const char s[],int Nowcolor)
{
this->x=x;
this->y=y;
this->lenx=lenx;
this->leny=leny;
this->color1=color1;
this->color0=color0;
delete [] this->s;
int lens=strlen(s);
this->s=new char [lens];
for(int i=0;i<=lens;++i)
* (this->s+i)=s[i];
this->Print(1,Nowcolor);
if(lens!=lenx*leny) return 0;
else return 1;
}
bool Button::Check(int Nowcolor)
{
POINT APOINT;
GetCursorPos(&APOINT);
ScreenToClient(GetForegroundWindow(),&APOINT);
APOINT.y=APOINT.y/16;
APOINT.x=APOINT.x/8;
if(APOINT.x>=this->x&&APOINT.x<=this->x+this->lenx-1&&APOINT.y>=this->y&&APOINT.y<=this->y+this->leny-1)
{
if(this->nowpoint)
{
this->Print(0,Nowcolor);
this->nowpoint=0;
}
if((GetAsyncKeyState(VK_RBUTTON) & 0x8000) ? 1:0) return 1;
}
else
{
if(!this->nowpoint)
{
this->Print(1,Nowcolor);
this->nowpoint=1;
}
}
return 0;
}
void Button::Delete()
{
for(int i=0;i<this->leny;++i)
{
COORD pos = {this->x,this->y+i};
SetConsoleCursorPosition(handle,pos);
for(int j=0;j<this->lenx;++j)
{
printf(" ");
}
}
delete [] this->s;
}
int main ()
{
Button a;
a.SetButton(1,10,4,1,7,0x70,"abcd");
while(1)
{
if(a.Check())break;
}
a.Delete();
return 0;
}