Posts tagged handle
How to find the GdiObject type from handle.
0![]()
Gdi Objects are represented by handles. Basically all handles are just an integer inside. For instance, if you’re writing a function with accepts HFONT as parameter, its quite possible to pass a typecasted handle of other Gdi object. So how can you determine the real Gdi object type from the handle?
![]()
You can use the function – GetObjectType(). See the following code snippet.
// Get the Black Brush.
HGDIOBJ hGdiObj = GetStockObject( BLACK_BRUSH );
// Check the object type with handle.
if( OBJ_BRUSH == GetObjectType( hGdiObj ))
{
// Yes! The handle points to Gdi Brush.
}
So now add better error checking in your gdi routines.
![]()
The values that GetObjectType() returns are,
- OBJ_BITMAP – Bitmap
- OBJ_BRUSH – Brush
- OBJ_COLORSPACE – Color space
- OBJ_DC Device – Context
- OBJ_ENHMETADC – Enhanced metafile DC
- OBJ_ENHMETAFILE – Enhanced metafile
- OBJ_EXTPEN – Extended pen
- OBJ_FONT – Font
- OBJ_MEMDC – Memory DC
- OBJ_METAFILE – Metafile
- OBJ_METADC – Metafile DC
- OBJ_PAL – Palette
- OBJ_PEN – Pen
- OBJ_REGION – Region
![]()
Targeted Audience – Beginners.
GetCurrentThread() returns pseudo handle, not the real handle.
0![]()
For getting our thread handle, we usually call GetCurrentThread() api. But actually it returns a pseudo handle. A pseudo handle, is a special handle which represents the handle of current thread which uses it. Please see the following e.g. for more clarify.
1) Thread A gets its threadID by calling GetCurrentThread and Passed to Thread B.
2) Thread B needs to terminate Thread A. So it calls TerminateThread( handle passed by Thread A ).
3) But instead of terminating Thread A, Thread B will be terminated, because the handle passed by Thread A was pseudo and it will become Thread B’s handle when Thread B uses it.
Debug one GetCurrentThread() call and GetCurrentProcess() call and watch its return values. You can see what they returns are follows,
-
GetCurrentThread() – 0xfffffffe
-
GetCurrentProcess() – 0xffffffff
Ofcourse pseudo… isn’t it ?
![]()
For getting a real handle which represents your thread, create a duplicate handle by calling DuplicateHandle(). Please see the code block below.
HANDLE hRealHandle = 0;
DuplicateHandle( GetCurrentProcess(), // Source Process Handle.
GetCurrentThread(), // Source Handle to dup.
GetCurrentProcess(), // Target Process Handle.
&hRealHandle, // Target Handle pointer.
0, // Options flag.
TRUE, // Inheritable flag
DUPLICATE_SAME_ACCESS );// Options
// Now the hRealHandle contains a real handle for your thread.