Borys Panasiuk
Borys Panasiuk

Reputation: 75

Cannot delete printer from control panel via Win32 API on Windows 8.1 and Windows 10

I'm trying to delete the printer entry from Windows programmatically and it seems to work with TCP/IP printers but not with assigned to USB port. Actually, the printer entry disappears from Win32_Printer WMI collection but it still exists in "Control Panel - Devices and Printers". It has only name there without driver and additional info assigned. I was trying to do this via ManagementScope and via "DeletePrinter" Print Spooler API method. My code snippets:

ManagementScope:

ManagementScope scope = new ManagementScope(ManagementPath.DefaultPath);
scope.Connect();
SelectQuery query = new SelectQuery("select * from Win32_Printer WHERE Name LIKE '" + printerName + "'");
ManagementObjectSearcher search = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection printersCollection = search.Get();
foreach (ManagementObject printer in printersCollection)
   printer.Delete();

DeletePrinter:

[DllImport("winspool.drv", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
static extern bool DeletePrinter(IntPtr hPrinter);

[DllImport("winspool.drv", SetLastError = true)]
static extern int ClosePrinter(IntPtr hPrinter);

[DllImport("winspool.drv", CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern int OpenPrinter(string pPrinterName, out IntPtr phPrinter, IntPtr pDefault);

private static bool DeletePrinter(string printerName)
{
   var pd = new PRINTER_DEFAULTS { DesiredAccess = 8 | 4 | 0x000F0000 };
   var rawsize = Marshal.SizeOf(pd);
   var pdPtr = Marshal.AllocHGlobal(rawsize);
   Marshal.StructureToPtr(pd, pdPtr, true);
   IntPtr hPrinter;
   if (OpenPrinter(printerName, out hPrinter, pdPtr) != 0)
   {
      if (hPrinter != IntPtr.Zero)
      {
         var result = DeletePrinter(hPrinter);
         ClosePrinter(hPrinter);
         return result;
      }
   }
   return false;
}

Upvotes: 2

Views: 835

Answers (1)

Alexander A. Sharygin
Alexander A. Sharygin

Reputation: 281

I have the same issue. I've created support incident for Microsoft and they confirmed it is a bug in OS.

Upvotes: 1

Related Questions