作者在 2021-04-02 20:53:36 发布以下内容
这个按钮与CSS3的 :hover 动画比较像。
先放代码:
#include<windows.h>
LRESULT CALLBACK WindowProc(HWND hWnd,UINT uMessage,WPARAM wParam,LPARAM lParam){
static bool bMouseOn=false,bLastMouseOn=false;
static WORD wTime=0;
switch(uMessage){
case WM_PAINT:{
HDC hdc;
PAINTSTRUCT ps;
hdc=BeginPaint(hWnd,&ps);
HPEN hPen=(HPEN)CreatePen(PS_SOLID,5,RGB(0xaa,0xaa,0xaa));
HPEN hOldPen=(HPEN)SelectObject(hdc,hPen);
HBRUSH hBrush=(HBRUSH)CreateSolidBrush(RGB(0xff-0x55*wTime/1000,0xff-0x55*wTime/1000,0xff-0x55*wTime/1000));
HBRUSH hOldBrush=(HBRUSH)SelectObject(hdc,hBrush);
RoundRect(hdc,10,10,90,90,7,7);
SetBkMode(hdc,TRANSPARENT);
HFONT hFont=CreateFontA(20,8,0,0,FW_NORMAL,false,false,false,ANSI_CHARSET,OUT_CHARACTER_PRECIS,CLIP_CHARACTER_PRECIS,DEFAULT_QUALITY,FF_MODERN,"微软雅黑");
SelectObject(hdc,hFont);
SetTextColor(hdc,RGB(0xaa+0x55*wTime/1000,0xaa+0x55*wTime/1000,0xaa+0x55*wTime/1000));
RECT r={10,10,90,90};
DrawTextA(hdc,"按钮",4,&r,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
EndPaint(hWnd,&ps);
if(bMouseOn&&wTime<1000){
if(wTime+50>1000) wTime=1000;
else wTime+=50;
Sleep(13);
InvalidateRect(hWnd,NULL,0);
}else if(!bMouseOn&&wTime>0){
if(wTime<50) wTime=0;
else wTime-=50;
Sleep(13);
InvalidateRect(hWnd,NULL,0);
}
DeleteObject(hPen);DeleteObject(hBrush);DeleteObject(hFont);
return 0;
}
case WM_MOUSEMOVE:{
int X=LOWORD(lParam),Y=HIWORD(lParam);
if(X>=10&&X<=90&&Y>=10&&Y<=90){
bMouseOn=true;
SetCursor(LoadCursor(NULL,IDC_HAND));
}
else{
bMouseOn=false;
SetCursor(LoadCursor(NULL,IDC_ARROW));
}
if(bMouseOn!=bLastMouseOn){
bLastMouseOn=bMouseOn;
InvalidateRect(hWnd,NULL,0);
}
return 0;
}
case WM_LBUTTONUP:{
if(bMouseOn) SetCursor(LoadCursor(NULL,IDC_HAND));
return 0;
}
case WM_LBUTTONDOWN:{
if(bMouseOn) SetCursor(LoadCursor(NULL,IDC_HAND));
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
return DefWindowProcA(hWnd,uMessage,wParam,lParam);
}
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow){
WNDCLASSEXA wndc;
wndc.cbSize=sizeof(wndc);
wndc.style=CS_HREDRAW|CS_VREDRAW;
wndc.lpfnWndProc=WindowProc;
wndc.cbClsExtra=0;
wndc.cbWndExtra=0;
wndc.hInstance=hInstance;
wndc.hIcon=LoadIcon(NULL,IDI_APPLICATION);
wndc.hCursor=LoadCursor(NULL,IDC_ARROW);
wndc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
wndc.lpszMenuName=NULL;
wndc.lpszClassName="windowclass";
wndc.hIconSm=NULL;
RegisterClassExA(&wndc);
HWND hWnd=CreateWindowExA(
0,
"windowclass",
"window",
WS_SYSMENU|WS_MINIMIZEBOX|WS_CAPTION,
66,
66,
300,
300,
NULL,
NULL,
hInstance,
NULL);
if(hWnd==NULL)
return -1;
ShowWindow(hWnd,nCmdShow);
UpdateWindow(hWnd);
MSG msg;
while(GetMessageA(&msg,NULL,0,0)){
TranslateMessage(&msg);
DispatchMessageA(&msg);
}
return msg.wParam;
}
(其中微软雅黑在电脑上时会作为按钮字体,否则按钮将采用默认字体)
代码比较长,看着头晕的就直接看效果吧!
(鼠标不在按钮之上时的效果)
(鼠标在按钮之上时的效果,与上图之间有渐变,鼠标未显示是屏幕截图的问题)
(以下为动图)
编译一下试试吧!