Problem with drawing lines: Win GDI

Started by
2 comments, last by Fixxer 18 years ago
I get this error from the code below, copied directly from my book. ------ Build started: Project: Example 2, Configuration: Debug Win32 ------ Compiling... main.cpp .\main.cpp(175) : error C2440: 'initializing' : cannot convert from 'HGDIOBJ' to 'HPEN' Conversion from 'void*' to pointer to non-'void' requires an explicit cast Build log was saved at "file://c:\Documents and Settings\Owner\Desktop\Programming\Windows Game Programming Book\Chapter 4\Example 2\Example 2\Debug\BuildLog.htm" Example 2 - 1 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

void GameMain(HDC hdc, HWND hwnd)
{
	if(KEYDOWN(VK_ESCAPE))
		SendMessage(hwnd,WM_CLOSE,0,0);
	
	// create random pen
	HPEN rand_pen = CreatePen(PS_SOLID,1,RGB(rand()%255, rand()%255, rand()%255));

	// select the pen into context
	HPEN old_pen = SelectObject(hdc,rand_pen);  // LINE 175 *********

	// draw the line
	MoveToEx(hdc,rand()%400,rand()%400,NULL);
	LineTo(hdc,rand()%400,rand()%400);

	// restore old pen
	SelectObject(hdc,old_pen);

	// delete pen
	DeleteObject(rand_pen);
}


Advertisement
SelectObject returns an HGDIOBJ, not an HPEN. You need to cast it. Change the line to:
HPEN old_pen = (HPEN)SelectObject(hdc,rand_pen);

EDIT: A little offtopic, but you should avoid creating and destroying objects every frame like that. You should create it at startup and delete it at shutdown.

EDIT 2: Also, those colour values for the pen should ideally be rand()%256, otherwise you'll never get a completely white (255, 255, 255) pen.
when you get these types of errors:
.\main.cpp(175) : error C2440: 'initializing' : cannot convert from 'HGDIOBJ' to 'HPEN'Conversion from 'void*' to pointer to non-'void' requires an explicit cast

you need to do a cast, such as the one below.
HPEN old_pen = (HPEN)SelectObject(hdc,rand_pen);

edit: i've been beaten... arggggggh

Beginner in Game Development?  Read here. And read here.

 

thanks both of you =)

This topic is closed to new replies.

Advertisement