Can't change DEVMODE of a printer

♀尐吖头ヾ 提交于 2019-12-05 18:06:40

I modified your code in the following way, since I don't have any valid data for devmode_data:

devmode = d.PrinterSettings.GetHdevmode();
if (devmode != IntPtr.Zero) d.PrinterSettings.SetHdevmode(devmode);

and now there is no exception here.

Please, provide me with your data for devmode_data or check for your own, if it is valid or not!

Mitch

SetHdevmode expects an HGLOBAL. You can get an HGLOBAL from .Net via Marshal.AllocHGlobal. Then, you can use Marshal.Copy(byte[], int, IntPtr, int) to copy from your managed byte array to the HGLOBAL. See below:

var pDevMode = Marshal.AllocHGlobal(devmode_data.Length);
Marshal.Copy(devmode_data, 0, pDevMode, devmode_data.Length);

d.PrinterSettings.SetHdevmode(pDevMode);
Marshal.FreeHGlobal(pDevMode);

The byte array can be partially handled as a structure, but that will require p/Invoke definitions. The PrinterSettings class, however, will not accept a structure, so doing so would be unneeded in this case. Additionally, the DEVMODE structure is variable length to allow for printer drivers to add additional opaque data, so it would not be possible to convert without data loss.

See How can I save and restore `PrinterSettings`? for more.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!