Sign in to follow this  
Fixxer

Problem with drawing lines: Win GDI

Recommended Posts

Fixxer    100
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);
}


Share this post


Link to post
Share on other sites
Evil Steve    2017
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.

Share this post


Link to post
Share on other sites
Alpha_ProgDes    6935
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this