C#获取和设置系统的默认打印机,使用API
时间:2011-05-10 来源:zxf92183
既然是API的方式,那首先就是API的引用声明了。
using System.Runtime.InteropServices;
[DllImport("Winspool.drv", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool SetDefaultPrinter(string printerName); [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool GetDefaultPrinter(StringBuilder pszBuffer, ref int pcchBuffer); static string GetDefaultPrinter() { const int ERROR_FILE_NOT_FOUND = 2; const int ERROR_INSUFFICIENT_BUFFER = 122; int pcchBuffer = 0; if (GetDefaultPrinter(null, ref pcchBuffer)) { return null; } int lastWin32Error = Marshal.GetLastWin32Error(); if (lastWin32Error == ERROR_INSUFFICIENT_BUFFER) { StringBuilder pszBuffer = new StringBuilder(pcchBuffer); if (GetDefaultPrinter(pszBuffer, ref pcchBuffer)) { return pszBuffer.ToString(); } lastWin32Error = Marshal.GetLastWin32Error(); } if (lastWin32Error == ERROR_FILE_NOT_FOUND) { return null; } throw new Win32Exception(Marshal.GetLastWin32Error()); }
相关阅读 更多 +