Sunday, February 15, 2015

How to get DevMode hex string in .NET


Problem
I'm trying to integrate a .net dll with another language. The other language, Dex, needs printer settings as a hex string.


Solution
1. Get the PrinterSettings.DevMode byte array. There's a method called GetHdevmode() that returns an IntPtr.  See the code below for a wrapper that returns the byte array from the passed in PrinterSettings object.

2. Convert the byte array to a hex string. You can use BitConverter.ToString(<the dev mode byte array from step 1>).Replace("-", ""); 

   
Wrapper code for getting DevMode data
        public static byte[] GetDevModeData(this PrinterSettings settings)
        {
            //Contract.Requires(settings != null);

            byte[] devModeData;
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                // cer since hDevMode is not a SafeHandle
            }
            finally
            {
                var hDevMode = settings.GetHdevmode();
                try
                {
                    IntPtr pDevMode = NativeMethods.GlobalLock(hDevMode);
                    try
                    {
                        var devMode = (NativeMethods.DEVMODE)Marshal.PtrToStructure(
                            pDevMode, typeof(NativeMethods.DEVMODE));

                        var devModeSize = devMode.dmSize + devMode.dmDriverExtra;
                        devModeData = new byte[devModeSize];
                        Marshal.Copy(pDevMode, devModeData, 0, devModeSize);
                    }
                    finally
                    {
                        NativeMethods.GlobalUnlock(hDevMode);
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(hDevMode);
                }
            }
            return devModeData;
        }

No comments:

Post a Comment

There was an error in this gadget