如何在默认打印机上打印测试页?

时间:2010-09-14 15:06:51

标签: c# winforms

如何在默认打印机上打印测试页

使用C#Winform Code?

提前谢谢

3 个答案:

答案 0 :(得分:2)

要生成内置Windows测试页,您还可以对PrintUI.dll使用p / invoke。这是一个简单的类,可以让你这样做:

public static class PrintTestPageHelper
{
    [DllImport("printui.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern void PrintUIEntryW(IntPtr hwnd, 
        IntPtr hinst, string lpszCmdLine, int nCmdShow);

    /// <summary>
    /// Print a Windows test page.
    /// </summary>
    /// <param name="printerName">
    /// Format: \\Server\printer name, for example:
    /// \\myserver\sap3
    /// </param>
    public static void Print(string printerName)
    {
        var printParams = string.Format(@"/k /n{0}", printerName);
        PrintUIEntryW(IntPtr.Zero, IntPtr.Zero, printParams, 0);
    }
}

public class Program
{

    static void Main(string[] args)
    {
        PrintTestPageHelper.Print(@"\\printserver.code4life.com\sap3");

        Console.WriteLine("Press enter to exit.");
        Console.ReadLine();
    }

}

答案 1 :(得分:1)

使用WMI,特别是PrintTestPage类的Win32_Printer方法。

有关如何从C#执行WMI方法的信息,请参阅此MSDN文章:How To: Execute a Method

答案 2 :(得分:0)

正如ho1所说,WMI可以容纳你:

ManagementClass processClass = new ManagementClass("Win32_Printer");
ManagementBaseObject outP = processClass.InvokeMethod("PrintTestPage", null);
if (Convert.ToUInt32(outP["ReturnValue"]) != 0)
{
    MessageBox.Show("Failed to print test page.");
}

每当您在没有指定打印机的情况下在PrintDocument上调用print时,它当然会使用默认值:

PrintDocument doc = new PrintDocument();
doc.Print(); // will print a blank page