如何使用c#命令安装/添加虚拟打印机?

时间:2019-04-02 10:56:56

标签: c# .net printers

我正在尝试使用Windows桌面应用程序安装虚拟打印机(对于Windows的所有版本)。我希望此打印机在“打印”对话框的下拉列表中可用(尤其是从Office)。

我正在尝试使用以下代码:

public static void installPrinter(string printerName)
{
    string arg;

    arg = "printui.dll , PrintUIEntry /if /b " + "\"" + printerName + "\"" + @" /f C:\Windows\inf\ntprint.inf /r " + "\"" + "lpt1:" + "\"" + " /m " + "\"" + "Brother DCP-116C" + "\""; //initial args
    ProcessStartInfo p = new ProcessStartInfo();
    p.FileName = "rundll32.exe";
    p.Arguments = arg;
    p.WindowStyle = ProcessWindowStyle.Hidden;

    try
    {
        Process.Start(p);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.InnerException.ToString());
    }
}

但是它不起作用。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

经过大量研究,我使它可以在x84和x64平台上的win 7,8,8.1,10上运行(没有任何嵌入式驱动程序)。 这是代码:

public static void installPrinter(string printerName) //works on win 7,8,8.1,10 on both x84 and x64
       {
           //https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/rundll32-printui

           //  /if         Installs a printer by using an .inf file.
           //  /b[name]    Specifies the base printer name.
           //  /@[file]    Specifies a command-line argument file and directly inserts the text in that file into the command line.
           //  /f[file]    Species the Universal Naming Convention (UNC) path and name of the .inf file name or the output file name, depending on the task that you are performing. Use /F[file] to specify a dependent .inf file.
           //  /r[port]    Specifies the port name.
           //  /m[model]   Specifies the driver model name. (This value can be specified in the .inf file.)


           string arg;
           arg = "printui.dll , PrintUIEntry /if /b " + "\"" + printerName + "\"" + @" /f C:\Windows\inf\ntprint.inf /r " + "\"" + "lpt1:" + "\"" + " /m " + "\"" + "Generic / Text Only" + "\""; 
           ProcessStartInfo p = new ProcessStartInfo();
           p.FileName = "rundll32.exe";
           p.Arguments = arg;
           p.WindowStyle = ProcessWindowStyle.Hidden;

           try
           {
               Process.Start(p);
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.InnerException.ToString());
           }
       }