Why do I get ERROR_ACCESS_DENIED attempting to ope

2019-06-09 06:26发布

According to undocprint given a job ID it should be possible to retrieve the spool file for the job using OpenPrinter and ReadPrinter by opening the printer using a string with format "PrinterName,Job xxxx". The MSDN documentation lists this method as well, though with an additional space after the comma "PrinterName, Job xxxx".

Whenever I try to call this method from my test application (using either string format) I get ERROR_ACCESS_DENIED (Windows 8 x64). Why is this and what do I need to do to get this working?

I'm running the test app as admin and have no trouble pausing jobs or printers or accessing other information.

I know the ID I'm using is valid because for an invalid ID it returns ERROR_INVALID_PRINTER_NAME instead.

The code I'm using:

public static void OpenPrinter(String printerName,
                               ref IntPtr printerHandle,
                               ref PRINTER_DEFAULTS defaults) {
    if (OpenPrinter(printerName, ref printerHandle, ref defaults) == 0) {
        throw new Win32Exception(Marshal.GetLastWin32Error(),
                                 string.Format("Error getting access to printer: {0}", printerName));
    }
}

[DllImport("winspool.drv", EntryPoint = "OpenPrinterW", SetLastError = true, CharSet = CharSet.Unicode,
    ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern int OpenPrinter(String pPrinterName, ref IntPtr phPrinter, ref PRINTER_DEFAULTS pDefault);

[StructLayout(LayoutKind.Sequential)]
public struct PRINTER_DEFAULTS {
    public IntPtr pDatatype;
    public IntPtr pDevMode;
    public uint DesiredAccess;
}

2条回答
Explosion°爆炸
2楼-- · 2019-06-09 07:06

Turns out that pDefaults must be passed NULL and then everything works.

This requires changing the extern definition to take an IntPtr or similar.

I haven't seen any documentation about why this might be (in fact the MSDN docs state that this passing NULL should be the same as requesting USE access), but it definitely fixes the issue in our testing.

查看更多
孤傲高冷的网名
3楼-- · 2019-06-09 07:25

Permissions. Are you running with administrator rights?

查看更多
登录 后发表回答