Using FillRect() in C++

和自甴很熟 提交于 2019-12-10 13:18:49

问题


I am new to using Graphics in Visual C++. I am just trying to make a rectangle filled with a color. Need help to correct this...

RECT rect;
HDC hdc;
hdc=CreateDC(TEXT("DISPLAY"),NULL,NULL,NULL);
rect.left=30;
rect.right=100;
rect.top=50;
rect.bottom=200;
FillRect(hdc,&rect,(HBRUSH)(RGB(40,151,151)));

The error is:

ERROR: The variable 'rect' is being used without being initialized.


回答1:


This will normally be a warning, not an error. In this case, it also appears to be spurious.

It might work better if you initialize it something like:

HDC hdc=CreateDC(TEXT("DISPLAY"),NULL,NULL,NULL);
RECT rect = {30, 50, 100, 200};
HBRUSH brush = CreateSolidBrush(RGB(50, 151, 151));

FillRect(hdc, &rect, brush);

DeleteObject(brush);

Do note the use of CreateSolidBrush -- casting a color to an HBRUSH seems unlikely to work.




回答2:


Your code fails because of this code:

(HBRUSH)(RGB(40,151,151))

You cannot cast an RGB color to an HBRUSH in any meaningful way. The only way to obtain an HBRUSH is a ask the system to give you one.

So, you need to create a real brush using one of the API functions for that purpose. For example, CreateSolidBrush.

HBRUSH hBrush = CreateSolidBrush(RGB(40,151,151));

When you have finished with the brush, call DeleteObject to return resources to the system.

As a general rule, every time you write a cast, regard the code as very suspicious. Always endeavour to write code without casts.



来源:https://stackoverflow.com/questions/16110527/using-fillrect-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!