Use the DirectoryServices and the native ADSI interfaces to control printqueues and jobs.
Here is a sample to get you started:
using System;
using System.DirectoryServices;
using System.Runtime.InteropServices;
using activeds; // Import activeds.tlb interop assembly
/********************************************************************************
// needs a reference to the interop assembly generated by tlbimp.exe
// Compile with csc /r:activeds.dll adprinter.cs
********************************************************************************/
class Tester {
// Printer status flags - see SDK docs for status values (IADsPrintQueueOperations)
[Flags]
enum PrinterStatus {
Paused = 1,
DeletePending = 2,
Error = 3,
PaperJam = 4,
PaperOut = 5
}
public static void Main() {
DirectoryEntry printer = new DirectoryEntry("WinNT://servername/printqueuename", null, null, AuthenticationTypes.ServerBind);
Console.WriteLine(printer.Path);
PropertyCollection pcoll = printer.Properties;
try
{
foreach(string sc in pcoll.PropertyNames) {
Console.WriteLine(sc + ":\t" + (pcoll[sc])[0].ToString());
} Console.WriteLine("---------------------------------");
}
catch(COMException ex)
{
Console.WriteLine(ex.Message);
}
// Use the PrintqueueOperations interface to contol the printer Queue
IADsPrintQueueOperations po = printer.NativeObject as IADsPrintQueueOperations ;
if(po != null) {
if(po.Status == (int)PrinterStatus.Paused) // If paused resume else pause printer
po.Resume();
else
po.Pause();
// Use the IADsPrintJob to control individual printjobs
foreach(IADsPrintJob pj in po.PrintJobs()) {
Console.WriteLine("{0} - {1}", pj.Description, pj.Name);
IADsPrintJobOperations pjo = pj as IADsPrintJobOperations;
Console.WriteLine(pjo.Name);
// Use IADsPrintJob.Name as arg. to remove the job from the queue
po.PrintJobs().Remove(pj.Name);
}
} printer.Dispose();
}
}
通常情况下,请不要创建 PrinterSettings 的实例,而是改用 PrintDocument.PrinterSettings 来设置打印机的设置。
Public Sub Printing(printer As String)
Try
streamToPrint = New StreamReader(filePath)
Try
printFont = New Font("Arial", 10)
Dim pd As New PrintDocument()
AddHandler pd.PrintPage, AddressOf pd_PrintPage
' Specify the printer to use.
pd.PrinterSettings.PrinterName = printer
If pd.PrinterSettings.IsValid then
pd.Print()
Else
MessageBox.Show("Printer is invalid.")
End If
Finally
streamToPrint.Close()
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub