Why do I get ERROR_ACCESS_DENIED attempting to open a specific job using OpenPrinter?

流过昼夜 提交于 2019-12-10 11:49:14

问题


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;
}

回答1:


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.




回答2:


Permissions. Are you running with administrator rights?



来源:https://stackoverflow.com/questions/12866444/why-do-i-get-error-access-denied-attempting-to-open-a-specific-job-using-openpri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!