Advertisement

Weird behaviour in Winapi.

Started by April 28, 2018 03:13 PM
1 comment, last by Nypyren 6 years, 9 months ago

#include "stdafx.h"
#include<windows.h>
#include "Global.h"

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
void initBackBuffer(HWND hwnd);

HDC hBackDC = NULL;
HBITMAP hBackBitmap = NULL;

void draw(HWND hwnd) {
	HDC hWinDC = GetDC(hwnd);

	SetBitmapBits(hBackBitmap, HEIGHT * WIDTH * sizeof(DWORD), (const void*)(screenBuffer));
	BitBlt(hWinDC, 0, 0, WIDTH, HEIGHT, hBackDC, 0, 0, SRCCOPY);
	
	ReleaseDC(hwnd, hWinDC);
}

int WINAPI wWinMain(HINSTANCE hInstace, HINSTANCE hPrevInstace, LPWSTR lpCmdLine, int nCmdShow) {
	memset(screenBuffer, 0, sizeof(screenBuffer));
	MSG msg = { 0 };
	WNDCLASS wnd = { 0 };

	wnd.lpfnWndProc = WndProc;
	wnd.hInstance = hInstace;
	wnd.lpszClassName = L"Window";

	if (!RegisterClass(&wnd)) {
		return 0;
	}

	HWND hwnd = CreateWindowEx(NULL, wnd.lpszClassName, L"Window",
		WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, WIDTH, HEIGHT, NULL, NULL, hInstace, NULL);

	if (!hwnd) {
		return 0;
	}

	ShowWindow(hwnd, nCmdShow);
	UpdateWindow(hwnd);

	for (int j = 0; j <= 495; j++) {
		for (int i = 0; i < 512; i++) {
			screenBuffer[i * WIDTH + j] = 0x00FF0000;
		}
	}
	while (true) {
		if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
			if (msg.message == WM_QUIT) {
				break;
			}

			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		

		draw(hwnd);
	}

	return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){

	switch (msg){
		case WM_CREATE:
			initBackBuffer(hwnd);
			break;
		case WM_DESTROY:
			DeleteDC(hBackDC);
			DeleteObject(hBackBitmap);
			PostQuitMessage(0);
			break;
	}
	return DefWindowProc(hwnd, msg, wParam, lParam);
}

void initBackBuffer(HWND hwnd) {
	HDC hWinDC = GetDC(hwnd);

	hBackDC = CreateCompatibleDC(hWinDC);
	hBackBitmap = CreateCompatibleBitmap(hWinDC, WIDTH, HEIGHT); 
	SetBitmapBits(hBackBitmap, HEIGHT * WIDTH * sizeof(DWORD), (const void*)(screenBuffer));
	
	SelectObject(hBackDC, hBackBitmap);
	ReleaseDC(hwnd, hWinDC);
}

 

The output I am getting is :

Capture2.PNG.05fb9038cf5de01698a02c891eb1fa8c.PNG

 

The WIDTH and HEIGHT is both 512 pixels but I running 


	for (int j = 0; j <= 495; j++) {
		for (int i = 0; i < 512; i++) {
			screenBuffer[i * WIDTH + j] = 0x00FF0000;
		}
	}

from 0 to 495 so that means that my actual WIDTH is 495 pixels and not 512 pixels. Where did the rest of 512 - 495 pixels go ? 

 

I think the size you provide when creating the window sets the "Nonclient area" (includes the window borders), and the area you're painting to is the "Client area" (area within the borders).

If you want to make your client area 512x512, you need to make your window larger by adding the border sizes.  You can use GetSystemMetrics or AdjustWindowRectEx to help figure out how much larger you need to make the window.

This topic is closed to new replies.

Advertisement