110,557
社区成员
发帖
与我相关
我的任务
分享
using System.Runtime.InteropServices;
unsafe struct PRINTER_DEFAULTS
{
public void* pDatatype; // LPTSTR
public void* pDevMode; // LPDEVMODE
public uint DesiredAccess; // ACCESS_MASK
};
[DllImport("kernel32", SetLastError = true)]
static extern int GetLastError();
[DllImport("WinSpool.drv", SetLastError = true)]
static extern unsafe bool OpenPrinter
(string pPrinterName, int* phPrinter, void* pDefault);
[DllImport("WinSpool.drv", SetLastError = true)]
static extern bool ClosePrinter(int hPrinter);
[DllImport("WinSpool.drv", SetLastError = true)]
static extern unsafe bool SetPrinter
(int hPrinter, uint Level, void* pPrinter, uint Command);
const uint PRINTER_ACCESS_ADMINISTER = 0x00000004;
const uint PRINTER_STATUS_OFFLINE = 0x00000080;
const uint PRINTER_CONTROL_PAUSE = 1;
const uint PRINTER_CONTROL_RESUME = 2;
const uint PRINTER_CONTROL_PURGE = 3;
const uint PRINTER_CONTROL_SET_STATUS = 4;
// Open a printer for administration operations.
static unsafe int CSOpenPrinter(string printerName)
{
bool bResult;
int hPrinter;
PRINTER_DEFAULTS pd;
pd.pDatatype = null;
pd.pDevMode = null;
pd.DesiredAccess = PRINTER_ACCESS_ADMINISTER;
bResult = OpenPrinter(printerName, &hPrinter, &pd);
if (!bResult)
{
throw new ApplicationException("Cannot open printer '" +
printerName + "' " +
Marshal.GetLastWin32Error());
}
return hPrinter;
}
// Close the printer.
static void CSClosePrinter(int hPrinter)
{
if (!ClosePrinter(hPrinter))
{
throw new ApplicationException("Cannot close printer " +
Marshal.GetLastWin32Error());
}
}
// Pause printer.
static unsafe void CSPausePrinter(int hPrinter)
{
if (!SetPrinter(hPrinter, 0, null, PRINTER_CONTROL_PAUSE))
{
throw new ApplicationException("Cannot pause printer " +
Marshal.GetLastWin32Error());
}
}
// Delete printer.
static unsafe void CSDeletePrinter(int hPrinter)
{
if (!SetPrinter(hPrinter, 0, null, PRINTER_CONTROL_PURGE))
{
throw new ApplicationException("Cannot delete printer " +
Marshal.GetLastWin32Error());
}
}
// Resume printer.
static unsafe void CSResumePrinter(int hPrinter)
{
if (!SetPrinter(hPrinter, 0, null, PRINTER_CONTROL_RESUME))
{
throw new ApplicationException("Cannot resume printer " +
Marshal.GetLastWin32Error());
}
}
// Disable printer (offline).
static unsafe void CSDisablePrinter(int hPrinter)
{
if (!SetPrinter(hPrinter, 0,
(byte*)PRINTER_STATUS_OFFLINE,
PRINTER_CONTROL_SET_STATUS))
{
throw new ApplicationException("Cannot disable printer " +
Marshal.GetLastWin32Error());
}
}
// Enable printer.
static unsafe void CSEnablePrinter(int hPrinter)
{
if (!SetPrinter(hPrinter, 0, (byte*)0, PRINTER_CONTROL_SET_STATUS))
{
throw new ApplicationException("Cannot enable printer " +
Marshal.GetLastWin32Error());
}
}
//
int hPrinter;
try
{
hPrinter = CSOpenPrinter("打印机名");
CSPausePrinter(hPrinter);
CSDeletePrinter(hPrinter);
CSClosePrinter(hPrinter);
}
catch
{
}