Graphics to Excel Printer Hdc


Nov 17, 2009

I'm working on a project in which I'm displaying many images in excel. For this reason, I'm not using shapes to store the pictures. I am currently drawing the pictures to the screen device context as the user scrolls up or down. Now I have to draw the images to the print preview and get them to print out correctly. I can draw the images to the dc of the print preview window "ExcelB", but I'm sure there is probably a better way to do this. Also, I'm drawing them in png format.



Nov 17, 2009
There is a dc for the print preview image and I am able to draw to this. The problem is that it isn't printing. I thought maybe it wasn't printing because it was originally a png file, and therefore the file type was causing a problem. Maybe it needs to come from a windows metafile? Here is sample code for drawing to the dc.

Visual Basic:
'handle for excel application
hwndApp = oApp.Hwnd
'handle for the workbook
hwndWb = FindWindowEx(hwndApp, 0&, "XLDesk", vbNullString)
'handle for the worksheet
hwndWs = FindWindowEx(hwndWb, 0&, "EXCEL7", vbNullString)
'get window rectangle size
retVal = GetWindowRect(hwndWs, wsRect)
x_offset = 21.5
y_offset = 13.5
'get dc of worksheet from the window handle
dcWs = GetDC(hwndWs)
'save the dc as a copy
oDC = SaveDC(dcWs)
'insert file path to a picture
Dim png As System.Drawing.Bitmap=System.Drawing.Bitmap.FromFile("")

'calculate rectancle over the cell
rect = GetRectangle(cell, cellOffset, png, x_offset, y_offset)
'create a graphic object from the dc
g = System.Drawing.Graphics.FromHdc(dcWs)
g.PageUnit = GraphicsUnit.Point
g.DrawImage(png, rect)
'restore the original dc
RestoreDC(dcWs, oDC)
retValue = ReleaseDC(hwndWs, dcWs)
Last edited by a moderator:


Ultimate Contributor
Jun 10, 2003
Is the output to the print preview DC what is printed? Or will the printer have it's own DC? I don't see any code drawing to either here. I don't know how much I can really help you here, seeing as I have no experience.


Nov 17, 2009
In the code that is posted, 'Excel7' is the window class for the worksheet. So, in this example it is drawing to the device context of the active sheet in excel. When the user clicks on 'Print Preview' a new window of class 'ExcelB' appears. If I draw on the dc of ExcelB, it will draw to the print preview window. Is it possible to get the dc for the printer when the user presses the print button, so I can manipulate this?
Top Bottom