// FUNCTION: SetPrinterDACL // // PURPOSE: Applies DACL to specified printer // // RETURN VALUE: true or false // // COMMENTS: static bool SetPrinterDACL(string szPrinterName, PACL pDacl) { var PrnDefs = new PRINTER_DEFAULTS { DesiredAccess = ACCESS_MASK.READ_CONTROL | ACCESS_MASK.WRITE_DAC }; if (!OpenPrinter(szPrinterName, out var hPrinter, PrnDefs)) { return(false); } using (hPrinter) { var NewSD = new SafePSECURITY_DESCRIPTOR(); if (!SetSecurityDescriptorDacl(NewSD, true, pDacl, false)) { return(false); } if (!SetPrinter(hPrinter, new PRINTER_INFO_3 { pSecurityDescriptor = NewSD })) { return(false); } } return(true); }
private static bool ChangePrinter(string printerName, PRINTER_CONTROL state) { IntPtr hPrinter; int iRes; PRINTER_DEFAULTS printerDefaults = new PRINTER_DEFAULTS(); printerDefaults.pDatatype = null; printerDefaults.pDevMode = null; printerDefaults.DesiredAccess = PRINTER_ALL_ACCESS; iRes = OpenPrinter(printerName, out hPrinter, printerDefaults); if (iRes == 0) { Console.WriteLine("[-] OpenPrinter failed: {0}", Marshal.GetLastWin32Error()); return(false); } iRes = SetPrinter(hPrinter, 0, IntPtr.Zero, state); if (iRes == 0) { Console.WriteLine("[-] SetPrinter failed: {0}", Marshal.GetLastWin32Error()); ClosePrinter(hPrinter); return(false); } ClosePrinter(hPrinter); return(true); }
public static PRINTER_INFO_2?GetPrinterInfo(String printerName) { IntPtr pHandle; PRINTER_DEFAULTS defaults = new PRINTER_DEFAULTS(); PRINTER_INFO_2? Info2 = null; OpenPrinter(printerName, out pHandle, ref defaults); Int32 cbNeeded = 0; bool bRet = GetPrinter(pHandle, 2, IntPtr.Zero, 0, out cbNeeded); if (cbNeeded > 0) { IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded); bRet = GetPrinter(pHandle, 2, pAddr, cbNeeded, out cbNeeded); if (bRet) { Info2 = (PRINTER_INFO_2)Marshal.PtrToStructure(pAddr, typeof(PRINTER_INFO_2)); } Marshal.FreeHGlobal(pAddr); } ClosePrinter(pHandle); return(Info2); }
public static bool CheckPrnJob(string pName) { int num1 = 0; int num2 = 10; int num3 = 1; pJob.PRINTER_DEFAULTS pd = new PRINTER_DEFAULTS(); pd.DesiredAccess = 983052; IntPtr hPrinter1 = new IntPtr(); bool flag; if (-(pJob.OpenPrinter(pName, ref hPrinter1, ref pd) ? 1 : 0) == 0) { flag = true; } else { int hPrinter2 = (int)hPrinter1; int FirstJob = num1; int NoJobs = num2; int Level = num3; IntPtr zero = IntPtr.Zero; ref IntPtr local1 = ref zero; int cdBuf = 0; int num4 = new int(); ref int local2 = ref num4;
public DRIVER_INFO_8?GetPrinterInfo(String printerName) { IntPtr pHandle; PRINTER_DEFAULTS defaults = new PRINTER_DEFAULTS(); DRIVER_INFO_8? Info8 = null; OpenPrinter(printerName, out pHandle, ref defaults); Int32 cbNeeded = 0; //GetPrinterDriver(IntPtr hPrinter, string pEnvironment, uint Level, IntPtr pDriverInfo, uint cbBuf, out uint pcbNeeded); bool bRet = GetPrinterDriver(pHandle, null, 8, IntPtr.Zero, 0, out cbNeeded); if (cbNeeded > 0) { IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded); bRet = GetPrinterDriver(pHandle, null, 8, pAddr, cbNeeded, out cbNeeded); if (bRet) { Info8 = (DRIVER_INFO_8)Marshal.PtrToStructure(pAddr, typeof(DRIVER_INFO_8)); } Marshal.FreeHGlobal(pAddr); } ClosePrinter(pHandle); return(Info8); }
internal static bool OpenExistingPrinter(string printerName, ref IntPtr pHandle) { PRINTER_DEFAULTS defaults = new PRINTER_DEFAULTS(); defaults.DesiredAccess = PRINTER_ALL_ACCESS; return(OpenPrinter(printerName, out pHandle, ref defaults)); }
private void DeletePrinter() { IntPtr hPrinter = IntPtr.Zero; PRINTER_DEFAULTS pDefaults = new PRINTER_DEFAULTS { DesiredAccess = PRINTER_ALL_ACCESS, pDatatype = IntPtr.Zero, pDevMode = IntPtr.Zero }; Exception failure = null; for (int nretries = 0; ; nretries++) { // Set the port to the default port before deleting the printer. // Otherwise, the delete may fail because the port is in use try { SetPort(_defaultPort); } catch { } if (OpenPrinter(_printerName, out hPrinter, ref pDefaults)) { try { // Retry the deletion of the printer for a second or so, just in case the spooler has not had time to clean up its last print job if (!DeletePrinter(hPrinter)) { if (nretries < 10) { Thread.Sleep(100); continue; } failure = new Win32Exception(Marshal.GetLastWin32Error()); } break; } finally { ClosePrinter(hPrinter); } } else { failure = new Win32Exception(Marshal.GetLastWin32Error()); break; } } if (failure != null) { if (PrinterExists(_printerName)) { throw failure; } } }
protected override void Run() { if (PagedData != null) { IntPtr hPrinter; PRINTER_DEFAULTS defaults = new PRINTER_DEFAULTS { DesiredAccess = PRINTER_ACCESS_MASK.PRINTER_ACCESS_USE, pDatatype = "RAW" }; if (OpenPrinter(PrinterName, out hPrinter, ref defaults)) { DOC_INFO_1 docInfo = new DOC_INFO_1 { Datatype = "RAW", DocName = JobName, OutputFile = null }; uint jobid = StartDocPrinter(hPrinter, 1, ref docInfo); if (jobid < 0) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } if (PagedData.Prologue != null) { WritePrinter(hPrinter, PagedData.Prologue); } if (PagedData.PageData != null) { foreach (byte[] pagedata in PagedData.PageData) { StartPagePrinter(hPrinter); WritePrinter(hPrinter, pagedata); EndPagePrinter(hPrinter); } } if (PagedData.Epilogue != null) { WritePrinter(hPrinter, PagedData.Epilogue); } if (!EndDocPrinter(hPrinter)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } ClosePrinter(hPrinter); } } }
/// <summary> /// Method Name : GetPrinterDuplex /// Programmatically get the Duplex flag for the specified printer /// driver's default properties. /// </summary> /// <param name="sPrinterName"> The name of the printer to be used. </param> /// <param name="errorMessage"> this will contain error messsage if any. </param> /// <returns> /// nDuplexSetting - One of the following standard settings: /// 0 = Error /// 1 = None (Simplex) /// 2 = Duplex on long edge (book) /// 3 = Duplex on short edge (legal) /// </returns> /// <remarks> /// </remarks> public short GetPrinterDuplex(string sPrinterName, out string errorMessage) { errorMessage = string.Empty; short functionReturnValue = 0; IntPtr hPrinter = default(IntPtr); PRINTER_DEFAULTS pd = default(PRINTER_DEFAULTS); DEVMODE dm = new DEVMODE(); int nRet = 0; pd.DesiredAccess = PRINTER_ACCESS_USE; nRet = OpenPrinter(sPrinterName, out hPrinter, ref pd); if ((nRet == 0) | (hPrinter.ToInt32() == 0)) { if (GetLastError() == 5) { errorMessage = "Access denied -- See the article for more info."; } else { errorMessage = "Cannot open the printer specified " + "(make sure the printer name is correct)."; } return(functionReturnValue); } nRet = DocumentProperties(IntPtr.Zero, hPrinter, sPrinterName, IntPtr.Zero, IntPtr.Zero, 0); if ((nRet < 0)) { errorMessage = "Cannot get the size of the DEVMODE structure."; goto cleanup; } IntPtr iparg = Marshal.AllocCoTaskMem(nRet + 100); nRet = DocumentProperties(IntPtr.Zero, hPrinter, sPrinterName, iparg, IntPtr.Zero, DM_OUT_BUFFER); if ((nRet < 0)) { errorMessage = "Cannot get the DEVMODE structure."; goto cleanup; } dm = (DEVMODE)Marshal.PtrToStructure(iparg, dm.GetType()); if (!Convert.ToBoolean(dm.dmFields & DM_DUPLEX)) { errorMessage = "You cannot modify the duplex flag for this printer " + "because it does not support duplex or the driver " + "does not support setting it from the Windows API."; goto cleanup; } functionReturnValue = dm.dmDuplex; cleanup: if ((hPrinter.ToInt32() != 0)) { ClosePrinter(hPrinter); } return(functionReturnValue); }
public IntPtr OpenPrinterHandle(string printerName) { var def = new PRINTER_DEFAULTS { pDatatype = null, pDevMode = IntPtr.Zero, DesiredAccess = OpenPrinterAccessCodes.PRINTER_ALL_ACCESS }; var hPrinter = IntPtr.Zero; if (!OpenPrinter(printerName, ref hPrinter, def)) { var lastWin32Error = new Win32Exception(Marshal.GetLastWin32Error()); Console.WriteLine("Failed open Printer: " + lastWin32Error.Message); throw lastWin32Error; } return(hPrinter); }
private bool PrinterExists(string printerName) { IntPtr hPrinter = IntPtr.Zero; PRINTER_DEFAULTS defaults = new PRINTER_DEFAULTS { DesiredAccess = PRINTER_ALL_ACCESS, pDatatype = IntPtr.Zero, pDevMode = IntPtr.Zero }; try { if (OpenPrinter(printerName, out hPrinter, ref defaults)) { ClosePrinter(hPrinter); return(hPrinter != IntPtr.Zero); } } catch { } return(false); }
public static int AddLocalPort(string portName) { PRINTER_DEFAULTS def = new PRINTER_DEFAULTS(); def.pDatatype = null; def.pDevMode = IntPtr.Zero; def.DesiredAccess = 1; //Server Access Administer IntPtr hPrinter = IntPtr.Zero; int n = OpenPrinter(",XcvMonitor Local Port", ref hPrinter, def); if (n == 0) { return(Marshal.GetLastWin32Error()); } if (!portName.EndsWith("\0")) { portName += "\0"; // Must be a null terminated string } // Must get the size in bytes. Rememeber .NET strings are formed by 2-byte characters uint size = (uint)(portName.Length * 2); // Alloc memory in HGlobal to set the portName IntPtr portPtr = Marshal.AllocHGlobal((int)size); Marshal.Copy(portName.ToCharArray(), 0, portPtr, portName.Length); uint needed; // Not that needed in fact... uint xcvResult; // Will receive de result here XcvData(hPrinter, "AddPort", portPtr, size, IntPtr.Zero, 0, out needed, out xcvResult); ClosePrinter(hPrinter); Marshal.FreeHGlobal(portPtr); return((int)xcvResult); }
public void RemoveJobs(String printerName) { IntPtr hPrinter; PRINTER_DEFAULTS defaults = new PRINTER_DEFAULTS { //PRINTER_ALL_ACCESS DesiredAccess = 0x000F000C, pDatatype = IntPtr.Zero, pDevMode = IntPtr.Zero }; if (OpenPrinter(printerName, out hPrinter, ref defaults) == false) { int errno = Marshal.GetLastWin32Error(); throw new Win32Exception(errno); } if (hPrinter == IntPtr.Zero) { int errno = Marshal.GetLastWin32Error(); throw new Win32Exception(errno); } //3 == PRINTER_CONTROL_PURGE => Entfernt alle Jobs! if (SetPrinter(hPrinter, 0, IntPtr.Zero, 3) == false) { int errno = Marshal.GetLastWin32Error(); throw new Win32Exception(errno); } if (ClosePrinter(hPrinter) == false) { int errno = Marshal.GetLastWin32Error(); throw new Win32Exception(errno); } }
public void UninstallPrinter(String printerName) { IntPtr hPrinter; PRINTER_DEFAULTS defaults = new PRINTER_DEFAULTS { //PRINTER_ALL_ACCESS DesiredAccess = 0x000F000C, pDatatype = IntPtr.Zero, pDevMode = IntPtr.Zero }; if (OpenPrinter(printerName, out hPrinter, ref defaults) == false) { int errno = Marshal.GetLastWin32Error(); throw new Win32Exception(errno); } if (hPrinter == IntPtr.Zero) { int errno = Marshal.GetLastWin32Error(); throw new Win32Exception(errno); } if (DeletePrinter(hPrinter) == false) { int errno = Marshal.GetLastWin32Error(); throw new Win32Exception(errno); } if (ClosePrinter(hPrinter) == false) { int errno = Marshal.GetLastWin32Error(); throw new Win32Exception(errno); } }
private static extern int OpenPrinter( string pPrinterName, out IntPtr hPrinter, PRINTER_DEFAULTS pDefault);
private static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, ref PRINTER_DEFAULTS pd);
internal static extern bool OpenPrinter2([MarshalAs(UnmanagedType.LPWStr)] string szPrinter, out IntPtr hPrinter, PRINTER_DEFAULTS pd);
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, ref PRINTER_DEFAULTS pd);
public static extern int OpenPrinter(string pPrinterName, out IntPtr phPrinter, ref PRINTER_DEFAULTS pDefault);
public static extern bool OpenPrinter2( string pPrintername, out IntPtr phPrinter, ref PRINTER_DEFAULTS pDefault, ref PRINTER_OPTIONS pOptions );
/// <summary> /// Method Name : SetPrinterDuplex /// Programmatically set the Duplex flag for the specified printer driver's default properties. /// </summary> /// <param name="sPrinterName"> sPrinterName - The name of the printer to be used. </param> /// <param name="nDuplexSetting"> /// nDuplexSetting - One of the following standard settings: /// 1 = None /// 2 = Duplex on long edge (book) /// 3 = Duplex on short edge (legal) /// </param> /// <param name="errorMessage"> this will contain error messsage if any. </param> /// <returns> /// Returns: True on success, False on error. /// </returns> /// <remarks> /// /// </remarks> public bool SetPrinterDuplex(string sPrinterName, int nDuplexSetting, out string errorMessage) { errorMessage = string.Empty; bool functionReturnValue = false; IntPtr hPrinter = default(IntPtr); PRINTER_DEFAULTS pd = default(PRINTER_DEFAULTS); PRINTER_INFO_9 pinfo = new PRINTER_INFO_9(); DEVMODE dm = new DEVMODE(); IntPtr ptrPrinterInfo = default(IntPtr); int nBytesNeeded = 0; int nRet = 0; Int32 nJunk = default(Int32); if ((nDuplexSetting < 1) | (nDuplexSetting > 3)) { errorMessage = "Error: dwDuplexSetting is incorrect."; return(functionReturnValue); } pd.DesiredAccess = PRINTER_ACCESS_USE; nRet = OpenPrinter(sPrinterName, out hPrinter, ref pd); if ((nRet == 0) | (hPrinter.ToInt32() == 0)) { if (GetLastError() == 5) { errorMessage = "Access denied -- See the article for more info."; } else { errorMessage = "Cannot open the printer specified " + "(make sure the printer name is correct)."; } return(functionReturnValue); } nRet = DocumentProperties(IntPtr.Zero, hPrinter, sPrinterName, IntPtr.Zero, IntPtr.Zero, 0); if ((nRet < 0)) { errorMessage = "Cannot get the size of the DEVMODE structure."; goto cleanup; } IntPtr iparg = Marshal.AllocCoTaskMem(nRet + 100); nRet = DocumentProperties(IntPtr.Zero, hPrinter, sPrinterName, iparg, IntPtr.Zero, DM_OUT_BUFFER); if ((nRet < 0)) { errorMessage = "Cannot get the DEVMODE structure."; goto cleanup; } dm = (DEVMODE)Marshal.PtrToStructure(iparg, dm.GetType()); if (!Convert.ToBoolean(dm.dmFields & DM_DUPLEX)) { errorMessage = "You cannot modify the duplex flag for this printer " + "because it does not support duplex or the driver " + "does not support setting it from the Windows API."; goto cleanup; } dm.dmDuplex = (short)nDuplexSetting; Marshal.StructureToPtr(dm, iparg, true); nRet = DocumentProperties(IntPtr.Zero, hPrinter, sPrinterName, pinfo.pDevMode, pinfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER); if ((nRet < 0)) { errorMessage = "Unable to set duplex setting to this printer."; goto cleanup; } GetPrinter(hPrinter, 9, IntPtr.Zero, 0, ref nBytesNeeded); if ((nBytesNeeded == 0)) { errorMessage = "GetPrinter failed."; goto cleanup; } ptrPrinterInfo = Marshal.AllocCoTaskMem(nBytesNeeded + 100); nRet = GetPrinter(hPrinter, 9, ptrPrinterInfo, nBytesNeeded, ref nJunk) ? 1 : 0; if ((nRet == 0)) { errorMessage = "Unable to get shared printer settings."; goto cleanup; } pinfo = (PRINTER_INFO_9)Marshal.PtrToStructure(ptrPrinterInfo, pinfo.GetType()); pinfo.pDevMode = iparg; pinfo.pSecurityDescriptor = 0; Marshal.StructureToPtr(pinfo, ptrPrinterInfo, true); nRet = SetPrinter(hPrinter, 9, ptrPrinterInfo, 0) ? 1 : 0; if ((nRet == 0)) { errorMessage = "Unable to set shared printer settings."; } functionReturnValue = Convert.ToBoolean(nRet); cleanup: if ((hPrinter.ToInt32() != 0)) { ClosePrinter(hPrinter); } return(functionReturnValue); }
private static extern bool OpenPrinter(string pPrinterName, out IntPtr phPrinter, ref PRINTER_DEFAULTS pPrinterDefaults);
/// <summary> /// Deletes a printer from the designated server. Must have administrator access to it. /// </summary> /// <param name="sServer"></param> /// <param name="sPrinter"></param> public static void DeletePrinter(CredentialEntry ce, string sServer, string sPrinter) { Session.EnsureNullSession(sServer, ce); // first, open the printer string s = Canon(sServer) + @"\" + sPrinter; int hPrinter; PRINTER_DEFAULTS pd = new PRINTER_DEFAULTS(); pd.pDatatype = IntPtr.Zero; pd.pDevMode = IntPtr.Zero; pd.DesiredAccess = PRINTER_ALL_ACCESS; IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(pd)); Marshal.StructureToPtr(pd, p, false); if (!OpenPrinter(s, out hPrinter, p)) { // free memory Marshal.DestroyStructure(p, typeof(PRINTER_DEFAULTS)); Marshal.FreeHGlobal(p); int nError = Marshal.GetLastWin32Error(); Win32Exception we = new Win32Exception(nError); if (nError == nErrorAccessDenied) { throw new AuthException(we); } else { throw we; } } Marshal.DestroyStructure(p, typeof(PRINTER_DEFAULTS)); Marshal.FreeHGlobal(p); // now remove it from AD PRINTER_INFO_7 pi7 = new PRINTER_INFO_7(); pi7.pszObjectGUID = IntPtr.Zero; pi7.dwAction = (uint) DSPRINT_OPTIONS.DSPRINT_UNPUBLISH; p = Marshal.AllocHGlobal(Marshal.SizeOf(pi7)); Marshal.StructureToPtr(pi7, p, false); SetPrinter(hPrinter, 7, p, 0); // NOTE: we swallow any error since the operation may be left in a "pending" state rather // than returning success or failure right away. // free memory Marshal.DestroyStructure(p, typeof(PRINTER_INFO_7)); Marshal.FreeHGlobal(p); // finally, remove the printer if (!DeletePrinter(hPrinter)) { int nError = Marshal.GetLastWin32Error(); Win32Exception we = new Win32Exception(nError); if (nError == nErrorAccessDenied) { throw new AuthException(we); } else { throw we; } } }
/// <summary> /// Deletes a printer from the designated server. Must have administrator access to it. /// </summary> /// <param name="sServer"></param> /// <param name="sPrinter"></param> public static void DeletePrinter(CredentialEntry ce, string sServer, string sPrinter) { Session.EnsureNullSession(sServer, ce); // first, open the printer string s = Canon(sServer) + @"\" + sPrinter; int hPrinter; PRINTER_DEFAULTS pd = new PRINTER_DEFAULTS(); pd.pDatatype = IntPtr.Zero; pd.pDevMode = IntPtr.Zero; pd.DesiredAccess = PRINTER_ALL_ACCESS; IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(pd)); Marshal.StructureToPtr(pd, p, false); if (!OpenPrinter(s, out hPrinter, p)) { // free memory Marshal.DestroyStructure(p, typeof(PRINTER_DEFAULTS)); Marshal.FreeHGlobal(p); int nError = Marshal.GetLastWin32Error(); Win32Exception we = new Win32Exception(nError); if (nError == nErrorAccessDenied) { throw new AuthException(we); } else { throw we; } } Marshal.DestroyStructure(p, typeof(PRINTER_DEFAULTS)); Marshal.FreeHGlobal(p); // now remove it from AD PRINTER_INFO_7 pi7 = new PRINTER_INFO_7(); pi7.pszObjectGUID = IntPtr.Zero; pi7.dwAction = (uint)DSPRINT_OPTIONS.DSPRINT_UNPUBLISH; p = Marshal.AllocHGlobal(Marshal.SizeOf(pi7)); Marshal.StructureToPtr(pi7, p, false); SetPrinter(hPrinter, 7, p, 0); // NOTE: we swallow any error since the operation may be left in a "pending" state rather // than returning success or failure right away. // free memory Marshal.DestroyStructure(p, typeof(PRINTER_INFO_7)); Marshal.FreeHGlobal(p); // finally, remove the printer if (!DeletePrinter(hPrinter)) { int nError = Marshal.GetLastWin32Error(); Win32Exception we = new Win32Exception(nError); if (nError == nErrorAccessDenied) { throw new AuthException(we); } else { throw we; } } }
public static bool PrintDocument(string printerName, string fileName) { FileStream fileStream = new FileStream(fileName, FileMode.Open); BinaryReader binaryReader = new BinaryReader(fileStream); Byte[] bytes = new Byte[fileStream.Length]; IntPtr pUnmanagedBytes = new IntPtr(0); Int32 nLength; UInt32 nWritten; PRINTER_DEFAULTS printerDefaults = new PRINTER_DEFAULTS(); DOC_INFO_1 docinfo1 = new DOC_INFO_1(); IntPtr hPrinter; int iRes; nLength = Convert.ToInt32(fileStream.Length); bytes = binaryReader.ReadBytes(nLength); pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength); Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength); printerDefaults.pDatatype = null; printerDefaults.pDevMode = null; printerDefaults.DesiredAccess = PRINTER_ACCESS_USE; iRes = OpenPrinter(printerName, out hPrinter, printerDefaults); if (iRes == 0) { Console.WriteLine("[-] OpenPrinter failed: {0}", Marshal.GetLastWin32Error()); Marshal.FreeCoTaskMem(pUnmanagedBytes); return(false); } docinfo1.pDocName = "RAW document"; docinfo1.pOutputFile = null; docinfo1.pDatatype = "RAW"; iRes = StartDocPrinter(hPrinter, 1, docinfo1); if (iRes == 0) { Console.WriteLine("[-] StartDocPrinter failed: {0}", Marshal.GetLastWin32Error()); ClosePrinter(hPrinter); Marshal.FreeCoTaskMem(pUnmanagedBytes); return(false); } iRes = StartPagePrinter(hPrinter); if (iRes == 0) { Console.WriteLine("[-] StartPagePrinter failed: {0}", Marshal.GetLastWin32Error()); EndDocPrinter(hPrinter); ClosePrinter(hPrinter); Marshal.FreeCoTaskMem(pUnmanagedBytes); return(false); } iRes = WritePrinter(hPrinter, pUnmanagedBytes, (uint)nLength, out nWritten); if (iRes == 0) { Console.WriteLine("[-] WritePrinter failed: {0}", Marshal.GetLastWin32Error()); EndPagePrinter(hPrinter); EndDocPrinter(hPrinter); ClosePrinter(hPrinter); Marshal.FreeCoTaskMem(pUnmanagedBytes); return(false); } EndPagePrinter(hPrinter); EndDocPrinter(hPrinter); ClosePrinter(hPrinter); Marshal.FreeCoTaskMem(pUnmanagedBytes); return(true); }
OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, ref PRINTER_DEFAULTS pd);
public static extern bool OpenPrinter([In] string pPrinterName, out IntPtr phPrinter, [In][MarshalAs(UnmanagedType.LPStruct)] PRINTER_DEFAULTS pDefault);
static extern bool OpenPrinter(string pPrinterName, out IntPtr phPrinter, ref PRINTER_DEFAULTS pDefault);
public static bool NewPrinter(string printerName, string portName, string driverName) { IntPtr hMonitor; IntPtr hPrinter; bool bRes; int iRes; uint size, needed, xcvResult; PRINTER_DEFAULTS printerDefaults = new PRINTER_DEFAULTS(); printerDefaults.pDatatype = null; printerDefaults.pDevMode = null; printerDefaults.DesiredAccess = SERVER_ACCESS_ADMINISTER; hMonitor = IntPtr.Zero; iRes = OpenPrinter(",XcvMonitor Local Port", out hMonitor, printerDefaults); if (iRes == 0) { Console.WriteLine("[-] Error opening printer handle: {0}\n", Marshal.GetLastWin32Error()); return(false); } if (!portName.EndsWith("\0")) { portName += "\0"; } size = (uint)(portName.Length * 2); IntPtr portPtr = Marshal.AllocHGlobal((int)size); Marshal.Copy(portName.ToCharArray(), 0, portPtr, portName.Length); bRes = XcvData(hMonitor, "AddPort", portPtr, size, IntPtr.Zero, 0, out needed, out xcvResult); if (bRes == false) { Console.WriteLine("[-] Failed to add port: {0}\n", Marshal.GetLastWin32Error()); Marshal.FreeHGlobal(portPtr); ClosePrinter(hMonitor); return(false); } iRes = InstallPrinterDriverFromPackage(null, null, driverName, null, 0); if (iRes != 0) { Console.WriteLine("[-] Failed to install print driver: {0}\n", Marshal.GetLastWin32Error()); Marshal.FreeHGlobal(portPtr); ClosePrinter(hMonitor); return(false); } PRINTER_INFO_2 printerinfo2 = new PRINTER_INFO_2(); printerinfo2.pPortName = portName; printerinfo2.pDriverName = driverName; printerinfo2.pPrinterName = printerName; printerinfo2.pPrintProcessor = "WinPrint"; printerinfo2.pDatatype = "RAW"; printerinfo2.pComment = "I'd be careful with this one..."; printerinfo2.pLocation = "Inside of an exploit"; printerinfo2.Attributes = PRINTER_ATTRIBUTE_RAW_ONLY | PRINTER_ATTRIBUTE_HIDDEN; printerinfo2.AveragePPM = 9001; hPrinter = IntPtr.Zero; hPrinter = AddPrinter(null, 2, printerinfo2); if (hPrinter == IntPtr.Zero) { Console.WriteLine("[-] Failed to create printer: {0}\n", Marshal.GetLastWin32Error()); Marshal.FreeHGlobal(portPtr); ClosePrinter(hMonitor); return(false); } Marshal.FreeHGlobal(portPtr); ClosePrinter(hMonitor); ClosePrinter(hPrinter); return(true); }