在這裡我用STRUCT和指向函數的指針定義結合實現了模擬鼠標類,並用它來寫了橡皮筋畫線法
#include <stdio.h>
#include <graphics.h>
#include <dos.h>
typedef struct
{
void (*Inits)();/*初始化鼠標驅動*/
int (*MButton)();/*按鍵位置與按鍵狀態*/
void (*MouseIco)();/*畫鼠標光標*/
int x;/*橫向坐標*/
int y;/*豎向坐標*/
int ox;
int oy;
int button;/*按鍵標志*/
}MOUSE;/*鼠標類*/
void mInits();
int mMButton();
void mMouseIco();
union REGS rg;
int main()
{
MOUSE *pM,mouse;
int graphdrive=0,graphmode=0;
int tracking=0,x1,y1,ox1,oy1;
pM=&mouse;
pM->Inits=mInits;
pM->MButton=mMButton;
pM->MouseIco=mMouseIco;
initgraph(&graphdrive,&graphmode,"");
setbkcolor(1);
setwritemode(1);/*畫線模式*/
pM->Inits(&pM->x,&pM->y);
pM->ox=pM->x;
pM->oy=pM->y;
do
{
pM->button=pM->MButton(&pM->x,&pM->y);
pM->MouseIco(&pM->x,&pM->y,&pM->ox,&pM->oy);
if(pM->button==1)
{
if(!tracking)/*捕捉開關*/
{
ox1=x1=pM->x;
oy1=y1=pM->y;
tracking=1;
}
if(pM->x!=ox1pM->y!=oy1)
{
line(x1,y1,ox1,oy1);
ox1=pM->x;
oy1=pM->y;
line(x1,y1,pM->x,pM->y);
}
}
else tracking=0;
}while(pM->button!=3);
}
void mInits(int *mx,int *my)
{
rg.x.ax=0;
int86(0x33,&rg,&rg);
if(rg.x.ax==0)
exit(1);
rg.x.ax=7;
rg.x.cx=2;
rg.x.dx=640;
int86(0x33,&rg,&rg);
rg.x.ax=8;
rg.x.cx=2;
rg.x.dx=480;
int86(0x33,&rg,&rg);
rg.x.ax=4;
*mx=rg.x.cx=640/2;
*my=rg.x.dx=480/2;
int86(0x33,&rg,&rg);
rectangle(rg.x.cx-2,rg.x.dx-2,rg.x.cx+2,rg.x.dx+2);
}
int mMButton(int *lx,int *ly)
{
rg.x.ax=3;
int86(0x33,&rg,&rg);
*lx=rg.x.cx;
*ly=rg.x.dx;
return rg.x.bx;
}
void mMouseIco(int *x,int *y,int *oldx,int *oldy)
{
if(*x!=*oldx*y!=*oldy)
{
rectangle(*oldx-2,*oldy-2,*oldx+2,*oldy+2);
*oldx=*x;
*oldy=*y;
rectangle(*x-2,*y-2,*x+2,*y+2);
}
}