Can I print a standard test page in code-behind in .NET 3.5?

后端 未结 2 1117
萌比男神i
萌比男神i 2021-01-23 07:05

Is there a way to print a standard test page in WPF from C# code if I have the name of a network printer?

Thanks!

2条回答
  •  一整个雨季
    2021-01-23 07:16

    The following is an example of using the System.Management namespace to access WMI and print a Test Page to a Printer. This relies on the Printer being connected to the Computer, I can provide code for connecting a Network printer through System.Management if you want that as well. This code should work for any version of the .Net Framework

    using System;
    using System.Management;
    
    public class PrintTestPageUsingWMI
    {
        private String _name;
        private ManagementObject _printer = null;
    
        public PrintTestPageUsingWMI(String printerName)
        {
            this._name = printerName;
    
            //Find the Win32_Printer which is a Network Printer of this name
    
            //Declare WMI Variables
            ManagementObject MgmtObject;
            ManagementObjectCollection MgmtCollection;
            ManagementObjectSearcher MgmtSearcher;
    
            //Perform the search for printers and return the listing as a collection
            MgmtSearcher = new ManagementObjectSearcher("Select * from Win32_Printer");
            MgmtCollection = MgmtSearcher.Get();
    
            foreach (ManagementObject objWMI in MgmtCollection)
            {
                if (objWMI.Item("sharename").ToString().Equals(this._name))
                {
                    this._printer = objWMI;
                }
            }
    
            if (this._printer == null)
            {
                throw new Exception("Selected Printer is not connected to this Computer");
            }        
        }
    
        public void PrintTestPage()
        {
            this.InvokeWMIMethod("PrintTestPage");
        }
    
        /// 
        /// Helper Method which Invokes WMI Methods on this Printer
        /// 
        /// The name of the WMI Method to Invoke
        /// 
        private void InvokeWMIMethod(String method) {
            if (this._printer == null)
            {
                throw new Exception("Can't Print a Test Page on a Printer which is not connected to the Computer");
            }
    
            Object[] objTemp = new Object[0] { null };
            ManagementObject objWMI;
    
            //Invoke the WMI Method
            this._printer.InvokeMethod(method, objTemp);
        }
    }
    

    Alternatively you could look at the System.Printing Namespace which is supported in .Net 3.0 and higher

提交回复
热议问题