MFC 点左键开始⼀暂停一个无限循环

2025-04-17 07:55:28
推荐回答(1个)
回答1:

#include 

static int flag = 0;
static int txtpos = 0;

LRESULT CALLBACK wndproc(HWND hw, UINT msg, WPARAM wp, LPARAM lp)
{
switch (msg) {
case WM_NCDESTROY:
PostQuitMessage(0);
return 0;
case WM_LBUTTONDOWN:
flag = !flag;
return 0;
case WM_ERASEBKGND:
return 1;
default:
return DefWindowProc(hw, msg, wp, lp);
}
}

int APIENTRY WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmd, INT nShow)
{
WNDCLASS wc;
ZeroMemory(&wc, sizeof(wc));
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = wndproc;
wc.lpszClassName = TEXT("mywnd");
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
RegisterClass(&wc);

HWND h = CreateWindow(TEXT("mywnd"), TEXT("这是一个窗口"), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 300, 300, NULL, NULL, hInst, 0);
ShowWindow(h, nShow);
UpdateWindow(h);

MSG msg;
for(;;) {
BOOL r;
if (flag == 1)
r = PeekMessage(&msg, 0, 0, 0, PM_REMOVE);
else {
r = GetMessage(&msg, 0, 0, 0);
if (r <= 0) break;
}
if (r > 0) {
if (msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
} else {
if (flag == 1) {
HDC dc = GetDC(h);
RECT rect;
GetClientRect(h, &rect);

HBRUSH bg = CreateSolidBrush(RGB(255, 255, 255));
SetTimer(h, 1, 33, 0);

const TCHAR str[] = TEXT("哇哈哈");

while(flag == 1) {
GetMessage(&msg, 0, 0, 0);
if (msg.message == WM_TIMER) {
txtpos -= 5;
if (txtpos < 0)
txtpos = rect.right;
FillRect(dc, &rect, bg);
TextOut(dc, txtpos, 50, str, sizeof(str)/sizeof(*str) - 1);
ValidateRect(h, NULL);
} else if (msg.message == WM_QUIT) {
PostQuitMessage(msg.wParam);
break;
} else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

DeleteObject(bg);
KillTimer(h, 1);

ReleaseDC(h, dc);
}
}
}
}

仅供参考


对了还有,我看了你的代码,怎么看也不像MFC,所以我的用API写了