private static void AddPort(string portName, int protocol, int portNumber, string address, string queue, bool snmpEnabled = false, string snmpCommunity = "public", int snmpDevIndex = 1) { if (PortExists(portName)) { LogDebug($"Port '{portName}' already exists."); return; } LogDebug($"Creating port '{portName}'."); using (SafePrinterHandle xcvMonitor = NativeMethods.OpenXcvMonitor()) { var portData = new NativeMethods.PortData { PortName = portName, Protocol = (uint)protocol, PortNumber = (uint)portNumber, IPAddress = address, HostAddress = address, Queue = queue, SnmpEnabled = snmpEnabled ? 1U : 0U, SnmpCommunity = snmpCommunity, SnmpDevIndex = (uint)snmpDevIndex, Version = 1, Reserved = 0, Size = (uint)Marshal.SizeOf <NativeMethods.PortData>() }; NativeMethods.XcvPortData(xcvMonitor, "AddPort", portData); LogDebug($"Port '{portName}' created."); } }
internal static void XcvPortData(SafePrinterHandle xcvMonitor, string command, object portData) { // TCPMON XCV commands are listed at https://msdn.microsoft.com/en-us/windows/hardware/drivers/print/tcpmon-xcv-commands int size = Marshal.SizeOf(portData); using (SafeUnmanagedMemoryHandle inputDataPointer = new SafeUnmanagedMemoryHandle(size)) { Marshal.StructureToPtr(portData, inputDataPointer.DangerousGetHandle(), true); if (!XcvData(xcvMonitor, command, inputDataPointer, (uint)size, IntPtr.Zero, 0, out uint outputNeededSize, out uint status)) { throw new Win32Exception(); } } }
/// <summary> /// Deletes the specified print port. /// </summary> /// <param name="portName">The port name.</param> /// <exception cref="Win32Exception">The underlying operation failed.</exception> public static void DeletePort(string portName) { if (!PortExists(portName)) { LogDebug($"Port '{portName}' does not exist."); return; } LogDebug($"Deleting port '{portName}'."); using (SafePrinterHandle xcvMonitor = NativeMethods.OpenXcvMonitor()) { var portData = new NativeMethods.DeletePortData() { PortName = portName, Version = 1, Reserved = 0 }; NativeMethods.XcvPortData(xcvMonitor, "DeletePort", portData); LogDebug($"Port '{portName}' deleted."); } }
internal static extern bool XcvData(SafePrinterHandle hXcv, string pszDataName, SafeUnmanagedMemoryHandle pInputData, uint cbInputData, IntPtr pOutputData, uint cbOutputData, out uint pcbOutputNeeded, out uint pdwStatus);
internal static extern bool OpenPrinter(string pPrinterName, out SafePrinterHandle phPrinter, ref PrinterDefaults pDefault);