Components for Developers & PDF Software → Virtual Printer C# Tutorials

How to create Virtual Printer using C#

 

How to print files programmatically using the ShellExecute function

The code sample below demonstrates how to print files programmatically on either a physical or a virtual printer using the ShellExecute function. It also demonstrates how to change the default system printer.

[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool GetDefaultPrinter(StringBuilder szPrinter,
	ref int bufferSize);

[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDefaultPrinter(string szPrinter);

void PrintDocumentUsingShellExecute (string  szPrinter, string DocumentPath)
{
    StringBuilder szDefaultPrinter = new StringBuilder(256);
    int bufferSize = szDefaultPrinter.Capacity;

    //get the default printer
    GetDefaultPrinter(szDefaultPrinter, ref bufferSize);

    // change the default printer
    if (String.Compare(szPrinter, szDefaultPrinter.ToString(), true) != 0)
    {
        SetDefaultPrinter(szPrinter);
    }

    // send the document to the print
    Process printProcess = new Process();
    printProcess.StartInfo.FileName = myDocument;
    printProcess.StartInfo.Verb = "Print";
    printProcess.StartInfo.CreateNoWindow = true;
    printProcess.Start();

    // set default printer back to original
    if (String.Compare(szPrinter, szDefaultPrinter, true) != 0)
    {
        SetDefaultPrinter(szDefaultPrinter);
    }
}

Then it's necessary to call these functions with the required parameters. For example, you can print MS Word and PDF documents this way:

PrintDocumentUsingShellExecute("Your Virtual Printer", 
						"c:\Documents\AnyDocument.doc")
PrintDocumentUsingShellExecute("Your Virtual Printer", 
						"c:\ Documents \AnyDocument.pdf")

Virtual Printer menu

Latest news

December 12 2011
Our driver now supports Windows 8

Send us your comments

We're really eager to hear from you. Please send us your suggestions in one of two ways: