views:

391

answers:

1

I am working on CrystalReports for VS2005.I need to change the default printer to some other printer and no.of copies to 2 as compared to the default of 1.

I have succeeded to change the default printer using below code.

static int SetAsDefaultPrinter(string printerDevice)
    {
        int ret = 0;
        try
        {

            string path = "win32_printer.DeviceId='" + printerDevice + "'";
            using (ManagementObject printer = new ManagementObject(path))
            {
                ManagementBaseObject outParams =
                printer.InvokeMethod("SetDefaultPrinter",
                null, null);
                ret = (int)(uint)outParams.Properties["ReturnValue"].Value;                
            }
        }

How to change no. of copies.

+1  A: 

.Net Framework doesnot provide any mechanism to ovverride the default print functionality.So i disabled the default print button and added a button name Print.Code for the event handler follows below.

 private void Print_Click(object sender, EventArgs e)
    {
        try
        {          
            PrintDialog printDialog1 = new PrintDialog();              
            PrintDocument pd = new PrintDocument();

            printDialog1.Document = pd;
            printDialog1.ShowNetwork = true;
            printDialog1.AllowSomePages = true;
            printDialog1.AllowSelection = false;
            printDialog1.AllowCurrentPage = false;
            printDialog1.PrinterSettings.Copies = (short)this.CopiesToPrint;                
            printDialog1.PrinterSettings.PrinterName = this.PrinterToPrint;
            DialogResult result = printDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                PrintReport(pd);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    private void PrintReport(PrintDocument pd)
    {
        ReportDocument rDoc=(ReportDocument)crvReport.ReportSource;
        rDoc.PrintOptions.PrinterName = pd.PrinterSettings.PrinterName; //This line helps,In case user selects a different printer other than the default selected.
        rDoc.PrintToPrinter(pd.PrinterSettings.Copies, false, pd.PrinterSettings.FromPage, pd.PrinterSettings.ToPage); // In place of Frompage and ToPage put 0,0 to print all pages,however in that case user wont be able to choose selection.
    }
Rohit
If you change the default printer here, does it have any ramifications for the system/other applications?
Anthony K
no it does not.It just changes it for that moment only.
Rohit