tags:

views:

690

answers:

5

I have an object, dc, of type CDC and I'd like to get an HDC object.

I read the MSDN documentation here, but don't really understand it.

Can someone provide me with a brief example/explanation on how to do this?

+1  A: 
HDC hDC = dc;
bdonlan
+2  A: 

Just assign it.

CDC cdc = something.
HDC hdc = cdc;
if (hdc != 0)
{
  //success...
}
ChrisW
+4  A: 

CDC class has operator HDC() defined which allows the compiler to convert a CDC object to HDC implicitly. Hence if you have CDC* and a function which takes HDC then you just dereference the pointer and send it to the function.

Naveen
Ok, thank you! I don't run into the 'operator' keyword too much, so it threw me off.
samoz
+1  A: 

CDC is a C++ class which - to a reasonable approximation - encapsulates an HDC, which is a handle to a device context.

The documenation which you link to describes a conversion operator, which is a C++ construct that classes can supply to allow implicit conversion from an instance of a class to some other type. In this case the implicit conversion results in the underlying handle (HDC) which the CDC instance encapsulates.

You can perform the conversion by using a CDC instance anywhere were it needs to be converted to an HDC.

Most simply:

void f( const CDC& cdc )
{
    HDC hdc = cdc;

    // use hdc here
}
Charles Bailey
+3  A: 

When you have CDC object it will be implicitly converted to HDC when necessary:

CDC dc;
HDC hdc = dc; // HDC hdc = dc.operator HDC();

If you have pointer to CDC object then using function GetSafeHdc will look more clear:

CDC* pdc = SOME;
HDC hdc = pdc->GetSafeHdc();
Kirill V. Lyadvinsky