非托管Print Spooler API winspool.drv 中有一个函数。您可以调用GetDefaultPrinter函数返回默认打印机的名称。
这是非托管函数的 P/Invoke 签名:
[DllImport("winspool.drv", CharSet=CharSet.Auto, SetLastError=true)]
private static extern bool GetDefaultPrinter(
StringBuilder buffer,
ref int bufferSize);
使用该函数判断是否设置了默认打印机:
public static bool IsDefaultPrinterAssigned()
{
//initialise size at 0, used to determine size of the buffer
int size = 0;
//for first call provide a null StringBuilder and 0 size to determine buffer size
//return value will be false, as the call actually fails internally setting the size to the size of the buffer
GetDefaultPrinter(null, ref size);
if (size != 0)
{
//default printer set
return true;
}
return false;
}
使用该函数返回默认的打印机名称,如果没有设置默认则返回空字符串:
public static string GetDefaultPrinterName()
{
//initialise size at 0, used to determine size of the buffer
int size = 0;
//for first call provide a null StringBuilder and 0 size to determine buffer size
//return value will be false, as the call actually fails internally setting the size to the size of the buffer
GetDefaultPrinter(null, ref size);
if (size == 0)
{
//no default printer set
return "";
}
StringBuilder printerNameStringBuilder = new StringBuilder(size);
bool success = GetDefaultPrinter(printerNameStringBuilder, ref size);
if (!success)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return printerNameStringBuilder.ToString();
}
在控制台应用程序中测试的完整代码:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
namespace DefaultPrinter
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(IsDefaultPrinterAssigned());
Console.WriteLine(GetDefaultPrinterName());
Console.ReadLine();
}
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool GetDefaultPrinter(
StringBuilder buffer,
ref int bufferSize);
public static bool IsDefaultPrinterAssigned()
{
//initialise size at 0, used to determine size of the buffer
int size = 0;
//for first call provide a null StringBuilder to and 0 size to determine buffer size
//return value will be false, as the call actually fails internally setting the size to the size of the buffer
GetDefaultPrinter(null, ref size);
if (size != 0)
{
//default printer set
return true;
}
return false;
}
public static string GetDefaultPrinterName()
{
//initialise size at 0, used to determine size of the buffer
int size = 0;
//for first call provide a null StringBuilder to and 0 size to determine buffer size
//return value will be false, as the call actually fails internally setting the size to the size of the buffer
GetDefaultPrinter(null, ref size);
if (size == 0)
{
//no default printer set
return "";
}
StringBuilder printerNameStringBuilder = new StringBuilder(size);
bool success = GetDefaultPrinter(printerNameStringBuilder, ref size);
if (!success)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return printerNameStringBuilder.ToString();
}
}
}