English 中文(简体)
How can I use c# to set printersettings?
原标题:

EDIT I have tried to reconstruct code I no longer have to show. I think it is just a klimitation of the printersetting class not exposing functionality that can be selected by using a dialog. It seems I should be able to configure and assign a printerSettings object to a PrintDocument and then print that PrintDocument...??? Am I not thinking right here or??

EDIT AGAIN I think all the setters sit of the printerSettings.DefaultPageSettings . This will allow me to modify the printersettings. I haven t proved it yet but will later

PrintDocument pd = new PrintDocument();
pd.DocumentName = "test.doc";

PrinterSettings printerSettings = new PrinterSettings();
printerSettings.?? <- I want to set the printer setting here e.g. DL, A4, etc
pd.PrinterSettings = printerSettings;
pd.Print();

I have generate word mail merge documents in c# (cheques, letters, documents) but all of these require different printer settings (cheque = custom setting, letters = DL Env,documents= A4)

I have these settings saved and can access them when loading the printer preferences dialog but I would like to be able to build it into code instead of manually changing the printer settings. I ve looked around and it seems printer settings class should be it but I can t seem to get it to work.

example psuedo code of what I am trying to do

//create the mail merge
IList<Letter> letters = MailMerge.Create(enum.letters)
Printer.Print(letters) //<-- in here I am trying set the printing preferences to DL Env


//create the mail merge
IList<Document> docs = MailMerge.Create(enum.documents)
Printer.Print(docs) //<-- in here I am trying set the printing preferences to A4

any help appreciated.

thanks

问题回答

You could probably use WMI. My only WMI-experience is some C#-code for WMI to retrieve some printer-properties, I haven t tried to set any printer-properties, but I think that it should be possible. Maybe these MSDN-links and code can help you get started.

WMI Tasks: Printers and Printing shows the commands in VB-script. How To: Retrieve Collections of Managed Objects shows how to use a SelectQuery and enumeration. How To: Execute a Method shows how to execute a method :-).

EDIT: I just noticed this StackOverflow article: How do I programatically change printer settings ..., that seems to use WMI to change some printer-settings.

My retrieve-code looks like this:

    //using System.Management;

    private void GetPrinterProperties(object sender, EventArgs e)
    {
        // SelectQuery from:
        //    http://msdn.microsoft.com/en-us/library/ms257359.aspx
        // Build a query for enumeration of instances
        var query = new SelectQuery("Win32_Printer");
        // instantiate an object searcher
        var searcher = new ManagementObjectSearcher(query); 
        // retrieve the collection of objects and loop through it
        foreach (ManagementObject lPrinterObject in searcher.Get())
        {
            string lProps = GetWmiPrinterProperties(lPrinterObject);
            // some logging, tracing or breakpoint here...
        }
    }

    // log PrinterProperties for test-purposes
    private string GetWmiPrinterProperties(ManagementObject printerObject)
    {
        // Win32_Printer properties from:
        //    http://msdn.microsoft.com/en-us/library/aa394363%28v=VS.85%29.aspx
        return String.Join(",", new string[] {
                GetWmiPropertyString(printerObject, "Caption"),
                GetWmiPropertyString(printerObject, "Name"),
                GetWmiPropertyString(printerObject, "DeviceID"),
                GetWmiPropertyString(printerObject, "PNPDeviceID"),
                GetWmiPropertyString(printerObject, "DriverName"),
                GetWmiPropertyString(printerObject, "Portname"),
                GetWmiPropertyString(printerObject, "CurrentPaperType"),
                GetWmiPropertyString(printerObject, "PrinterState"),
                GetWmiPropertyString(printerObject, "PrinterStatus"),
                GetWmiPropertyString(printerObject, "Location"),
                GetWmiPropertyString(printerObject, "Description"),
                GetWmiPropertyString(printerObject, "Comment"),
            });
    }

    private string GetWmiPropertyString(ManagementObject mgmtObject, string propertyName)
    {
        if (mgmtObject[propertyName] == null)
        {
            return "<no "+ propertyName + ">";
        }
        else
        {
            return mgmtObject[propertyName].ToString();
        }
    }
}
    private void startPrintingButton_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        if (DialogResult.OK == ofd.ShowDialog(this))
        {
            PrintDocument pdoc = new PrintDocument();

            pdoc.DefaultPageSettings.PrinterSettings.PrinterName = "ZDesigner GK420d";
            pdoc.DefaultPageSettings.Landscape = true;
            pdoc.DefaultPageSettings.PaperSize.Height = 140;
            pdoc.DefaultPageSettings.PaperSize.Width = 104;

            Print(pdoc.PrinterSettings.PrinterName, ofd.FileName);
        }
    }

    private void Print(string printerName, string fileName)
    {
        try
        {
            ProcessStartInfo gsProcessInfo;
            Process gsProcess;

            gsProcessInfo = new ProcessStartInfo();
            gsProcessInfo.Verb = "PrintTo";
            gsProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
            gsProcessInfo.FileName = fileName;
            gsProcessInfo.Arguments = """ + printerName + """;
            gsProcess = Process.Start(gsProcessInfo);
            if (gsProcess.HasExited == false)
            {
                gsProcess.Kill();
            }
            gsProcess.EnableRaisingEvents = true;

            gsProcess.Close();
        }
        catch (Exception)
        {
        }
    }




相关问题
Bring window to foreground after Mutex fails

I was wondering if someone can tell me what would be the best way to bring my application to the foreground if a mutex was not able to be created for a new instance. E.g.: Application X is running ...

How to start WinForm app minimized to tray?

I ve successfully created an app that minimizes to the tray using a NotifyIcon. When the form is manually closed it is successfully hidden from the desktop, taskbar, and alt-tab. The problem occurs ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

Handle DataTable.DataRow cell change event

I have a DataTable that has several DataColumns and DataRow. Now i would like to handle an event when cell of this DataRow is changed. How to do this in c#?

Apparent Memory Leak in DataGridView

How do you force a DataGridView to release its reference to a bound DataSet? We have a rather large dataset being displayed in a DataGridView and noticed that resources were not being freed after the ...

ALT Key Shortcuts Hidden

I am using VS2008 and creating forms. By default, the underscore of the character in a textbox when using an ampersand is not shown when I run the application. ex. "&Goto Here" is not ...

WPF-XAML window in Winforms Application

I have a Winforms application coded in VS C# 2008 and want to insert a WPF window into the window pane of Winforms application. Could you explain me how this is done.

热门标签