Sharing HDC between different processes
I am writing some kind of IPC functionality and need to pass certain resources from one process to another. This works well for Pipe handles etc. which can be duplicated via DuplicateHandle. Now I need to pass a HDC from one process to the other. Is this even possible? If yes: how?
Sub-Question: I am assuming passing window handles (HWND) from one process to the other is safe开发者_运维技巧. Is this assumption correct?
HWNDs can be shared between processes, SendMessage() wouldn't work otherwise. They are however scoped to a specific desktop, a desktop is associated with a session. There is one session for each logged-in user. And session 0 is special, the session in which services run. And there's a secure desktop, the one you see at login or when you press Ctrl+Alt+Del, you cannot mess with the password entry box. But as long as both processes run in the same desktop you won't have any trouble.
HDCs are murky, never tried that. I wouldn't recommend it. You can always create one from a HWND with GetDC().
All GDI handles are stored in a table that is mapped into every process. The entries in the table contain the process id of the owning process, and this is checked on every GDI access to the handle.
So, (ironically), GDI handles - including HDCs - are valid system wide. But can only be used from the process that created them.
This Page documents the process affinity of GDI objects. Of course, as a counter point it is worth noting that some COM functions, and window messages like WM_PRINT do not have any interprocess restrictions and they ARE passed HDC's, so they clearly have to do something behind the scenes to marshal the HDC from one process to the next.
Assuming, that you want to paint onto a HDC belonging to one process from another process (e.g. by using BitBlt) then as pointed out by nobugz and Chris Becke you cannot share that HDC across process boundaries. But, further assuming that the HDC of that one process belongs to a window (and your intention is to finally draw onto that window) then you can pass that window handle to the other process and in this process use GetDc to obtain a HDC. With this HDC you can then paint onto the window of the other process.
精彩评论