Retrieving Device Context from .NET print API

2019-08-02 02:12发布

问题:

I am working on a .NET application to control DataCard Desktop Card printers, and I have stumbled upon a problem. In order to execute Magnetic Stripe and Chip encoding, I have to call a function in a native printer API dll to enable the printers Interactive mode.

I have managed to create the P/Invoke code to call this native function. But the problem is that this method takes the printer Device Context handle as a parameter, and have to be called BEFORE the Gdi32 StartDoc function is called.

In the .NET printing API I do have access to the hDC from the Graphics object. But as far as I can see the Graphics object is only availible AFTER the StartDoc function is invoked.

So my question is if anyone knows a way to retrieve the context before StartDoc is called?

回答1:

You can do a OpenPrinter to retrieve a printer handle (HANDLE) and then call CreateDC by passing in this handle to get a printer DC anytime (before StartDoc).