C# 使用 Windows API 发送文件到打印机
最近需要做一个打印的功能,于是在网上找到了这么一个方法。
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)]
public string pDocName;
[MarshalAs(UnmanagedType.LPStr)]
public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)]
public string pDataType;
} public class PrintCode
{
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd); [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di); [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten); /// <summary>
/// 该方法把非托管内存中的字节数组发送到打印机的打印队列
/// </summary>
/// <param name="szPrinterName">打印机名称</param>
/// <param name="pBytes">非托管内存指针</param>
/// <param name="dwCount">字节数</param>
/// <returns>成功返回true,失败时为false</returns>
public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = , dwWritten = ;
IntPtr hPrinter = new IntPtr();
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; di.pDocName = "My C#.NET RAW Document";
di.pDataType = "RAW"; try
{
// 打开打印机
if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
{
// 启动文档打印
if (StartDocPrinter(hPrinter, , di))
{
// 开始打印
if (StartPagePrinter(hPrinter))
{
// 向打印机输出字节
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
if (bSuccess == false)
{
dwError = Marshal.GetLastWin32Error();
}
}
catch (Win32Exception ex)
{
WriteLog(ex.Message);
bSuccess = false;
}
return bSuccess;
} /// <summary>
/// 发送文件到打印机方法
/// </summary>
/// <param name="szPrinterName">打印机名称</param>
/// <param name="szFileName">打印文件的路径</param>
/// <returns></returns>
public static bool SendFileToPrinter(string szPrinterName, string szFileName)
{
bool bSuccess = false;
try
{
// 打开文件
FileStream fs = new FileStream(szFileName, FileMode.Open); // 将文件内容读作二进制
BinaryReader br = new BinaryReader(fs); // 定义字节数组
Byte[] bytes = new Byte[fs.Length]; // 非托管指针
IntPtr pUnmanagedBytes = new IntPtr(); int nLength; nLength = Convert.ToInt32(fs.Length); // 读取文件内容到字节数组
bytes = br.ReadBytes(nLength); // 为这些字节分配一些非托管内存
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength); // 将托管字节数组复制到非托管内存指针
Marshal.Copy(bytes, , pUnmanagedBytes, nLength); // 将非托管字节发送到打印机
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength); // 释放先前分配的非托管内存
Marshal.FreeCoTaskMem(pUnmanagedBytes); fs.Close();
fs.Dispose();
}
catch (Win32Exception ex)
{
WriteLog(ex.Message);
bSuccess = false;
}
return bSuccess;
} /// <summary>
/// 将字符串发送到打印机方法
/// </summary>
/// <param name="szPrinterName">打印机名称</param>
/// <param name="szString">打印的字符串</param>
/// <returns></returns>
public static bool SendStringToPrinter(string szPrinterName, string szString)
{
bool flag = false;
try
{
IntPtr pBytes;
Int32 dwCount; // 获取字符串长度
dwCount = szString.Length; // 将字符串复制到非托管 COM 任务分配的内存非托管内存块,并转换为 ANSI 文本
pBytes = Marshal.StringToCoTaskMemAnsi(szString); // 将已转换的 ANSI 字符串发送到打印机
flag = SendBytesToPrinter(szPrinterName, pBytes, dwCount); // 释放先前分配的非托管内存
Marshal.FreeCoTaskMem(pBytes);
}
catch (Win32Exception ex)
{
WriteLog(ex.Message);
flag = false;
}
return flag;
} /// <summary>
/// 写入日志方法
/// </summary>
/// <param name="msg">记录信息</param>
public static void WriteLog(string msg)
{
string str = string.Empty;
string path = AppDomain.CurrentDomain.BaseDirectory + "log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; FileStream filestream = new FileStream(path, FileMode.OpenOrCreate); str += "************" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "************\r\n";
str += msg;
str += "************" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "************\r\n"; FileStream fs = new FileStream(path, FileMode.Append);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
sw.WriteLine(str); sw.Flush(); sw.Close();
sw.Dispose(); fs.Close();
fs.Dispose();
}
}
以上就是全部代码了,调用就很简单了,方法如下:
private void Print_Click(object sender, EventArgs e)
{
//打印文件的路径,该方法获取到的文件路径在应用程序 bin\Debug\ 目录下,所以 ../../ 向上两级目录
string fileName = AppDomain.CurrentDomain.BaseDirectory + @"../../File/demo.txt"; if (PrintCode.SendFileToPrinter("PrinterName", fileName))
{
MessageBox.Show("文件已成功发送至打印队列!","提示信息");
}
}
C# 使用 Windows API 发送文件到打印机的更多相关文章
- ansible管理windows (发送文件)
https://github.com/ansible/ansible/raw/devel/examples/scripts/ConfigureRemotingForAnsible.ps1 环境: 服务 ...
- 使用Windows API发送HTTP请求
先看一个简单的GET示例 #include <Windows.h> #include <winhttp.h> #include <stdio.h> int main ...
- MT4调用Windows API进行文件读写操作
/*导入相关函数*/ #import "kernel32.dll" int CreateDirectoryW(string directoryName,int type); int ...
- 【转】用C#调用Windows API向指定窗口发送
一.调用Windows API. C#下调用Windows API方法如下: 1.引入命名空间:using System.Runtime.InteropServices; 2.引用需要使用的方法,格式 ...
- 用C#调用Windows API向指定窗口发送按键消息 z
用C#调用Windows API向指定窗口发送 一.调用Windows API. C#下调用Windows API方法如下: 1.引入命名空间:using System.Runtime.Interop ...
- 用C#调用Windows API向指定窗口发送按键消息
一.调用Windows API. C#下调用Windows API方法如下: 1.引入命名空间:using System.Runtime.InteropServices; 2.引用需要使用的方法,格式 ...
- 用Windows API函数(CreateFile/ReadFile/WriteFile/CloseHandle)完成文件拷贝程序(初级版)
文件拷贝程序 程序类型:Console 参数:源文件名 目的文件名 要求:1.只能使用Windows API函数(CreateFile/ReadFile/WriteFile/CloseHandle ...
- LoadLibrary文件路径及windows API相关的文件路径问题
LoadLibrary HMODULE WINAPI LoadLibrary( _In_ LPCTSTR lpFileName ); Loads the specified module into ...
- 学习:Windows API核心DLL文件
在 Windows 的系统目录中,存在着很多的动态链接库文件(DLL 文件).这些 DLL 文件中包括了 Windows API 函数可执行程序. DLL 将各函数"导出",这样应 ...
随机推荐
- js post
在进行html5页面的设计时,希望用户加载完成页面后,进行交互时只改变其中的某些元素的内容,这样更像本地APP的呈现效果,但是HTML中的post.get如果使用submit进行提交的话会直接使用返回 ...
- 《linux系统及其编程》实验课记录(五)
实验 5:权限的设置和更改 实验环境: 安装了 Red Hat Enterprise Linux 6.0 可运行系统,并且是成功验证系统.有另外一个无特权用户 student,密码 student 的 ...
- thinkPHP隐藏url地址栏中的index.php方法
http://localhost/workSpace/First/index.php/Home/Index/index隐藏上面url中的index.php方法如下: 第一步.删除apache配置文件( ...
- hdu 3667(拆边+最小费用最大流)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3667 思路:由于花费的计算方法是a*x*x,因此必须拆边,使得最小费用流模板可用,即变成a*x的形式. ...
- C语言的代码内存布局详解
一个程序本质上都是由 BSS 段.data段.text段三个组成的.这样的概念在当前的计算机程序设计中是很重要的一个基本概念,而且在嵌入式系统的设计中也非常重要,牵涉到嵌入式系统运行时的内存大小分配, ...
- Android 模拟机出现Installation failed due to invalid URI!错误
[2017-03-28 09:52:13 - DataVDemo06] Installation failed due to invalid URI![2017-03-28 09:52:13 - Da ...
- IOS 7 自定义的UIAlertView不能在iOS7上正常显示
本文转载至 http://blog.csdn.net/hanbing861210/article/details/13614405 众所周知,当伟大的iOS7系统发布后,表扬的一堆.谩骂的也一片,而对 ...
- php事件钩子
PHP中钩子函数的实现与认识: http://rmingwang.com/set-php-hooks.html 1.钩子函数是预设并在特定的条件下触发的. 2.钩子函数接管程序后可以影响到程序的走向 ...
- android EditText自动弹出和自动关闭软键盘
程序进入某个activity直接弹出软键盘,不能直接在OnCreate中设置,必须等View绘制事件完毕才可以弹出,需要用到Timer辅助实现,如果要实现输入的功能,必须让EditText获得焦点. ...
- ng2-file-upload上传附件同时传参
由于业务需要,需要的场景是发某条公告的时候能够上传附件,不只是图片,图片的话可以直接用base64传给后台,但上传附件这个就不能这样干了, 与此同时,每条公告都有一个对应的唯一标识id, 附件以文件流 ...