在64位Windows 7上添加虚拟打印机时出错

时间:2012-07-05 21:41:05

标签: winapi printing

我们有一些用C#编写的打印服务器软件(来自winspool.drv的P / Invokes函数)。一些“打印机”实际上是print to a directory的虚拟打印机。安装这种打印机的代码是:

public override void AddLocalDirectoryPrinter(string printerName, string directory)
{
    IntPtr hPrinter = IntPtr.Zero;

    try
    {
        PRINTER_DEFAULTS pd;
        PRINTER_INFO_2 pi2;

        pd.datatype = null;
        pd.pDevMode = IntPtr.Zero;
        // Access = PRINTER_ALL_ACCESS
        // http://msdn.microsoft.com/en-us/library/cc244650%28v=prot.10%29.aspx
        pd.desiredAccess = PRINTER_ALL_ACCESS;

        // Attributes = PUBLISHED | DO_COMPLETE_FIRST | SHARED
        // http://msdn.microsoft.com/en-us/library/aa394363%28v=vs.85%29.aspx
        pi2.attributes = 0x2208;
        pi2.averagePpm = 0;
        pi2.jobs = 0;
        pi2.defaultPriority = 0;
        pi2.comment = "Auto-Generated by [name of program]";
        pi2.datatype = "RAW";
        pi2.pDevMode = IntPtr.Zero;
        pi2.driverName = "Generic / Text Only";
        pi2.location = string.Empty;
        pi2.parameters = string.Empty;
        pi2.portName = directory;
        pi2.printerName = printerName.ToUpperInvariant();
        pi2.printProcessor = "WinPrint";
        pi2.priority = 0;
        pi2.pSecurityDescriptor = IntPtr.Zero;
        pi2.sepFile = string.Empty;
        pi2.serverName = string.Empty;
        pi2.shareName = printerName.ToUpperInvariant();
        pi2.startTime = 0;
        pi2.status = 0;
        pi2.untilTime = 0;

        hPrinter = AddPrinter(null, 2, ref pi2);

        if (hPrinter == IntPtr.Zero)
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }
    }
    catch (Exception ex)
    {
        throw new PrintingException("Failed to add printer", ex);
    }
    finally
    {
        if (hPrinter != IntPtr.Zero)
        {
            ClosePrinter(hPrinter);
        }
    }
}

在32位Windows XP上,上面的代码运行没有错误。但是在64位Windows 7上,对AddPrinter的调用失败,Windows错误1796(“指定的端口未知”)。

为什么它适用于一个版本的Windows而不适用于另一个版本?

1 个答案:

答案 0 :(得分:0)

事实证明,我只需要构建一个64位版本的dirport.dll。