我需要用 C 语言而不是 C++ 语言创建一个 WinAPI 窗口。在C中,当我制作窗口时,它在调整大小时遇到问题。当我将其尺寸调整得更大时,它会形成一个黑色背景,其中有奇怪的白色斑点。解决这个问题的唯一方法就是将其设置为原始大小。C++ 不会发生这种情况。我怎样才能解决这个问题?它编译没有错误。
正常尺寸: 正确显示
最大化: 它会产生奇怪的效果。
代码:
wmain.h
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
const wchar_t* szWndClassName = L"WindowClass"; const wchar_t* szWndName = L"Notepad";
int width = 600, height = 400;
HINSTANCE hInst; HWND hWnd;
WNDCLASS wc;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
RECT rect;
int CenterWindow(HWND parent_window, int width, int height)
{
GetClientRect(parent_window, &rect);
rect.left = (rect.right / 2) - (width / 2);
rect.top = (rect.bottom / 2) - (height / 2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
wmain.c
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include "wmain.h"
#pragma warning (disable: 28251)
int WINAPI WinMain(HINSTANCE hThisInst, HINSTANCE hPrevInst, LPSTR lpszCMDArgs, int nCMDShow)
{
hInst = hThisInst;
wc.lpszClassName = szWndClassName;
wc.lpfnWndProc = WndProc;
wc.hInstance = hInst;
wc.hCursor = LoadCursor(wc.hInstance, L"IDC_ARROW");
wc.hIcon = LoadIcon(wc.hInstance, L"Resource Files/Images/Notepad.ico");
if (!RegisterClass(&wc))
{
MessageBox(NULL, L"RegisterClassW failed!", L"Error", MB_ICONERROR);
return 1;
}
CenterWindow(GetDesktopWindow(), width, height);
hWnd = CreateWindow(szWndClassName, szWndName, WS_OVERLAPPEDWINDOW, rect.left, rect.top, width, height, NULL, NULL, hInst, NULL);
if (!hWnd)
{
MessageBox(NULL, L"CreateWindowW failed!", L"Error", MB_ICONERROR);
return 2;
}
ShowWindow(hWnd, nCMDShow);
UpdateWindow(hWnd);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp)
{
switch (msg)
{
case WM_CREATE:
break;
case WM_COMMAND:
switch (wp)
{
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, msg, wp, lp);
}
}
Run Code Online (Sandbox Code Playgroud)
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
Run Code Online (Sandbox Code Playgroud)