Search code examples
c#winformsprintingprinter-properties

Printer properties Dialog Saved changes


Hi i want to save the changes i made in printer preferences but they are ignored . I am doing this in c# Please help me thanks

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    PrintDocument pd = new PrintDocument();

    [DllImport("kernel32.dll")]
    static extern IntPtr GlobalLock(IntPtr hMem);

    [DllImport("kernel32.dll")] 
    [return: MarshalAs(UnmanagedType.Bool)] static extern bool GlobalUnlock(IntPtr hMem);

    [DllImport("kernel32.dll")]
    static extern IntPtr GlobalFree(IntPtr hMem);

    [DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesW", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] 
    static extern int DocumentProperties(IntPtr hwnd, IntPtr hPrinter,[MarshalAs(UnmanagedType.LPWStr)] string pDeviceName,IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);                                                                                                                                                           
    private const int DM_IN_BUFFER = 8;
    private const int DM_OUT_BUFFER = 2;
    private const int DM_IN_PROMPT = 4;

    private void ShowPrinterProperties(PrinterSettings settings)
    {
        IntPtr hDevMode = settings.GetHdevmode(settings.DefaultPageSettings);

        IntPtr pDevMode = GlobalLock(hDevMode);

        DocumentProperties(this.Handle, IntPtr.Zero, settings.PrinterName, pDevMode, pDevMode, DM_IN_PROMPT);

        GlobalUnlock(hDevMode);

        settings.SetHdevmode(hDevMode);

        settings.DefaultPageSettings.SetHdevmode(hDevMode);

        GlobalFree(hDevMode);
    }

    private void Form1_Load(object sender, EventArgs e)
    {  
            // Add list of installed printers found to the combo box.
           // The pkInstalledPrinters string will be used to provide the display string.
           String pkInstalledPrinters;
           for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
           {
               pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
               comboBox1.Items.Add(pkInstalledPrinters);
               //selectedPrinter = comboBox1.SelectedItem.ToString();
           }
    }

    private void button1_Click(object sender, EventArgs e)
    {
           if (pd.PrinterSettings.IsValid)
               ShowPrinterProperties(pd.PrinterSettings);
           else
               MessageBox.Show("Invalid printer name");
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

        pd.PrinterSettings.PrinterName = comboBox1.Text;
       // selectedPrinter = comboBox1.SelectedItem.ToString();         

    }
}

Solution

  • This should do the trick, tried and tested (make sure you have references to System.Drawing, System.Printing and ReachFramework assemblies):

        public static bool GetPrinterProperties(PrinterDescription selectedPrinter, bool showPrintingPreferencesDialog)
        {
            int modeGetSizeOfBuffer = 0;
            int modeCopy = 2;
            int modeOutBuffer = 14;
    
            IntPtr pointerHDevMode = new IntPtr();
            IntPtr pointerDevModeData = new IntPtr();
    
            try
            {
                PrintTicketConverter printTicketConverter = new PrintTicketConverter(selectedPrinter.FullName, selectedPrinter.ClientPrintSchemaVersion);
                IntPtr mainWindowPtr = new WindowInteropHelper(Application.Current.MainWindow).Handle;
                PrinterSettings printerSettings = new PrinterSettings();
    
                pointerHDevMode = printerSettings.GetHdevmode(printerSettings.DefaultPageSettings);
                IntPtr pointerDevMode = GlobalLock(pointerHDevMode);
    
                int sizeNeeded = DocumentProperties(mainWindowPtr, IntPtr.Zero, selectedPrinter.FullName, IntPtr.Zero, pointerDevMode, modeGetSizeOfBuffer);
                pointerDevModeData = Marshal.AllocHGlobal(sizeNeeded);
    
                int result = -1;
    
                if (!showPrintingPreferencesDialog)
                {
                    result = DocumentProperties(mainWindowPtr, IntPtr.Zero, selectedPrinter.FullName, pointerDevModeData, pointerDevMode, modeCopy);
                }
                else
                {
                    result = DocumentProperties(mainWindowPtr, IntPtr.Zero, selectedPrinter.FullName, pointerDevModeData, pointerDevMode, modeOutBuffer);
                }
    
                GlobalUnlock(pointerHDevMode);
    
                if (result == 1)
                {
                    byte[] devMode = new byte[sizeNeeded];
                    Marshal.Copy(pointerDevModeData, devMode, 0, sizeNeeded);
    
                    // set back new printing settings to selected printer.
                    selectedPrinter.DefaultPrintTicket = printTicketConverter.ConvertDevModeToPrintTicket(devMode);
    
                    return true;
                }
            }
            finally
            {
                GlobalFree(pointerHDevMode);
                Marshal.FreeHGlobal(pointerDevModeData);
            }
    
            return false;
        }
    

    The PrinterDescription class is as follows:

        public class PrinterDescription
        {
            public string FullName { get; set; }
            public int ClientPrintSchemaVersion { get; set; }
            public PrintTicket DefaultPrintTicket { get; set; }
        }
    

    And the following imports are used:

        [DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesW", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        private static extern int DocumentProperties(IntPtr hwnd, IntPtr hPrinter, [MarshalAs(UnmanagedType.LPWStr)] string pDeviceName, IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);
    
        [DllImport("kernel32.dll")]
        private static extern IntPtr GlobalLock(IntPtr hMem);
    
        [DllImport("kernel32.dll")]
        private static extern bool GlobalUnlock(IntPtr hMem);
    
        [DllImport("kernel32.dll")]
        private static extern bool GlobalFree(IntPtr hMem);
    

    After the dialog is ok'd, the print ticket will be updated. You may want to return the print ticket here, or use a copy of the default.