在 C# 中打印到 LPT1

2024-03-16

如何在 C# 中使用文件 LPT1 直接打印到点阵打印机。

我用 fopen 在 C++ 上做到了这一点,但我不知道如何在 c# 中做到这一点。

非常感谢


在 Windows 中将打印机设置为“通用/仅文本”,然后打印到它。

这是我用来打印到具有自己的编码文本格式的标签打印机的代码。

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;

namespace whatever {

public class RawPrinterHelper
{
    // Structure and API declarions:
    [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;
    }
    [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);

    // SendBytesToPrinter()
    // When the function is given a printer name and an unmanaged array
    // of bytes, the function sends those bytes to the print queue.
    // Returns true on success, false on failure.
    public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
    {
        Int32 dwError = 0, dwWritten = 0;
        IntPtr hPrinter = new IntPtr(0);
        DOCINFOA di = new DOCINFOA();
        bool bSuccess = false; // Assume failure unless you specifically succeed.

        di.pDocName = "My C#.NET RAW Document";
        di.pDataType = "RAW";

        // Open the printer.
        if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
        {
            // Start a document.
            if (StartDocPrinter(hPrinter, 1, di))
            {
                // Start a page.
                if (StartPagePrinter(hPrinter))
                {
                    // Write your bytes.
                    bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
        // If you did not succeed, GetLastError may give more information
        // about why not.
        if (bSuccess == false)
        {
            dwError = Marshal.GetLastWin32Error();
        }
        return bSuccess;
    }

    public static bool SendFileToPrinter(string szPrinterName, string szFileName)
    {
        // Open the file.
        FileStream fs = new FileStream(szFileName, FileMode.Open);
        // Create a BinaryReader on the file.
        BinaryReader br = new BinaryReader(fs);
        // Dim an array of bytes big enough to hold the file's contents.
        Byte[] bytes = new Byte[fs.Length];
        bool bSuccess = false;
        // Your unmanaged pointer.
        IntPtr pUnmanagedBytes = new IntPtr(0);
        int nLength;

        nLength = Convert.ToInt32(fs.Length);
        // Read the contents of the file into the array.
        bytes = br.ReadBytes(nLength);
        // Allocate some unmanaged memory for those bytes.
        pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
        // Copy the managed byte array into the unmanaged array.
        Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
        // Send the unmanaged bytes to the printer.
        bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
        // Free the unmanaged memory that you allocated earlier.
        Marshal.FreeCoTaskMem(pUnmanagedBytes);
        return bSuccess;
    }
    public static bool SendStringToPrinter(string szPrinterName, string szString)
    {
        IntPtr pBytes;
        Int32 dwCount;
        // How many characters are in the string?
        dwCount = szString.Length;
        // Assume that the printer is expecting ANSI text, and then convert
        // the string to ANSI text.
        pBytes = Marshal.StringToCoTaskMemAnsi(szString);
        // Send the converted ANSI string to the printer.
        bool success = SendBytesToPrinter(szPrinterName, pBytes, dwCount);
        Marshal.FreeCoTaskMem(pBytes);
        return success;
    }
}
}

然后从另一个类调用它,如下所示:

    private bool PrintLabels(string printerName)
    {
        return RawPrinterHelper.SendStringToPrinter(printerName, this.Text);
    }

(编辑:如果有人看到任何与非托管资源相关的主要问题,请在评论中告诉我)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C# 中打印到 LPT1 的相关文章

  • 具有不同大小结构的结构数组的 malloc()

    如果每个结构都包含一个大小不同的字符串数组 那么如何正确地 malloc 一个结构数组 因此每个结构可能有不同的大小 并且不可能 realloc 结构体数量 sizeof 结构体名称 after malloc 初始大小 sizeof 结构名
  • Subversion 和 Visual Studio 项目的最佳实践

    我最近开始在 Visual Studio 中处理各种 C 项目 作为大型系统计划的一部分 该系统将用于替换我们当前的系统 该系统是由用 C 和 Perl 编写的各种程序和脚本拼凑而成的 我现在正在进行的项目已经达到了颠覆的临界点 我想知道什
  • 将字节数组转换为托管结构

    更新 这个问题的答案帮助我编写了开源项目GitHub 上的 AlicanC 现代战争 2 工具 https github com AlicanC AlicanC s Modern Warfare 2 Tool 你可以看到我是如何阅读这些数据
  • SFINAE 如何使用省略号?

    过去 当使用 SFINAE 选择构造函数重载时 我通常使用以下内容 template
  • 将字符串转换为正确的 URI 格式?

    有没有简单的方法可以将电子邮件地址字符串转换为正确的 URI 格式 Input http mywebsite com validate email 3DE4ED727750215D957F8A1E4B117C38E7250C33 email
  • HttpWebRequest vs Webclient(特殊场景)

    我知道这个问题之前已经回答过thread https stackoverflow com questions 1694388 webclient vs httpwebrequest httpwebresponse 但我似乎找不到详细信息 在
  • 两种类型的回发事件

    1 我发现了两篇文章 每篇文章对两种类型的回发事件的分类都略有不同 一位资源说两种类型的回发事件是Changed事件 其中控件实现 IPostbackDataHandler 当数据在回发之间更改时触发 然后Raised事件 其中控件实现 I
  • 从成员函数指针类型生成函子

    我正在尝试简化 通过make fn 预处理参数的函子的生成 通过wrap 对于 arity 的成员函数n 生成函子基本上可以工作 但到目前为止只能通过显式指定成员函数的参数类型来实现 现在我想从它处理的成员函数类型生成正确的函子 struc
  • 预处理后解析 C++ 源文件

    我正在尝试分析c 使用我定制的解析器的文件 写在c 在开始解析之前 我想摆脱所有 define 我希望源文件在预处理后可以编译 所以最好的方法是运行C Preprocessor在文件上 cpp myfile cpp temp cpp or
  • 分配器感知容器和propagate_on_container_swap

    The std allocator traits模板定义了一些常量 例如propagate on container copy move assign让其他容器知道它们是否应该在复制或移动操作期间复制第二个容器的分配器 我们还有propag
  • C# 中的常量和只读? [复制]

    这个问题在这里已经有答案了 可能的重复 const 和 readonly 之间有什么区别 https stackoverflow com questions 55984 what is the difference between cons
  • 如何随着分辨率的变化自动调整大小和调整表单控件

    我注意到某些应用程序会更改控件的位置以尽可能适应当前的分辨率 例如 如果窗口最大化 则控件的设置方式应使整个 GUI 看起来平衡 是否可以使用 C 在 Visual studio 2010 中制作或实现此功能 Use Dock http m
  • 从 R 到 C 处理列表并访问它

    我想使用从 R 获得的 C 列表 我意识到这个问题与此非常相似 使用 call 在 R 和 C 之间传递数据帧 https stackoverflow com questions 6658168 passing a data frame f
  • 使用 mingw32 在 Windows 上构建 glew 时“DllMainCRTStartup@12”的多个定义

    我关注了这个主题 使用 mingw 使建筑物在 Windows 上闪闪发光 https stackoverflow com questions 6005076 building glew on windows with mingw 6005
  • 从 Delphi 调用 C# dll

    我用单一方法编写了 Net 3 5 dll 由Delphi exe调用 不幸的是它不起作用 步骤 1 使用以下代码创建 C 3 5 dll public class MyDllClass public static int MyDllMet
  • 使用 HTMLAgilityPack 从节点的子节点中选择所有

    我有以下代码用于获取 html 页面 将网址设置为绝对 然后将链接设置为 rel nofollow 并在新窗口 选项卡中打开 我的问题是关于将属性添加到 a s string url http www mysite com string s
  • 受限 AppDomain 中的代码访问安全异常

    Goal 我需要在权限非常有限的 AppDomain 中运行一些代码 它不应该访问任何花哨或不安全的内容 except对于我在其他地方定义的一些辅助方法 我做了什么 我正在创建一个具有所需基本权限的沙箱 AppDomain 并创建一个运行代
  • 带有私有设置器的 EFCore Base 实体模型属性 - 迁移奇怪的行为

    实体模型继承的类内的私有设置器似乎会导致 EFCore 迁移出现奇怪的问题 考虑以下示例 其中有多个类 Bar and Baz 继承自Foo 跑步时Add Migration多次命令 添加 删除private修饰符 生成的模式在多个方面都是
  • 服务器响应 PASV 命令返回的地址与建立 FTP 连接的地址不同

    System Net WebException 服务器响应 PASV 命令返回的地址与建立 FTP 连接的地址不同 在 System Net FtpWebRequest CheckError 在 System Net FtpWebReque
  • C#中为线程指定特殊的cpu

    我有 2 个线程 我想告诉其中一个在第一个 cpu 上运行 第二个在第二个 cpu 上运行 例如在具有两个 cpu 的机器中 我怎样才能做到这一点 这是我的代码 UCI UCIMain new UCI Thread UCIThread ne

随机推荐

  • 从 XML 数据写入 SQLite 数据库

    给出以下代码来导出数据库中的每个表 string strSql SELECT FROM tableName SqliteConnection sqlCon new SqliteConnection Data Source dbPath us
  • 以编程方式设置 Angular 4 复选框

    我见过类似的问题 但我仍然不明白 我有一个组件女巫获取项目列表Array lt id number name string gt 以及 已检查 项目的列表Array
  • 这个编码字符串表示什么?您是如何发现的?

    我正在尝试建立一个产品目录 但我不知道它在做什么 我想看看里面 有人能弄清楚如何打印源代码并告诉我怎么做吗 FZrHbutatkV pXpVF2wwJ1S4YBZzjp0HRjGIOfPrH0 LgGFL5OZac45h e efvf5RH
  • 使用 StateFlow 和分页的 Android MVI 3

    我正在尝试使用状态流和分页 3 来实现 android MVI 架构 但是当我有一个包含分页数据的视图状态时 我感到很困惑 问题是我将视图模型中的视图状态公开为状态流对象 但现在在该视图状态内我有另一个来自分页库的流对象 状态流中可以有一个
  • 如何使用 Meteor 公开 RESTful Web 服务

    您将如何使用 Meteor 创建一个安静的 Web 服务 我想在 Appcelerator 中创建连接到同一后端的应用程序 Meteor 能解决这个问题吗 我在 Meteorpedia 上写了一篇完整的文章 http www meteorp
  • Entity Framework(EF5) 支持 XML 数据类型吗?

    我正在考虑在 SQL Server 2008 R2 中使用 XML 数据类型 同时也将 EF 与 MVC 结合使用 EF5 支持 XML 数据类型吗 如果没有 那么我将不得不选择不同的数据库设计 非常感谢 EF 目前不原生支持 Xml 类型
  • EJB 3.1 API 的 Maven 存储库

    我可以使用什么 Maven 存储库来实现 EJB 3 1 API 依赖项 这种对中央的依赖起了作用
  • 在哪里可以找到 scala.Any 和 scala.AnyRef 的定义?

    我想跳到 Any 的源代码来看看一些方法是如何实现的 但我发现它没有包含在 scala library src 中 AnyRef 也没有包含在其中 但是值类型和 Nothing 都包含在其中 我很好奇 Scala 对象基类型是如何以及在哪里
  • 如何从父对象获取对象的属性值

    我在这个结构中有对象 obj user name jeterson title I am a test 我有一把有价值的钥匙 user name 我试图获得这样的价值 obj key 意义obj user name 它不起作用 只适用于ob
  • WPF 4 多点触控拖放

    我有一个 WPF 4 应用程序 我使用标准实现了拖放DragDrop DoDragDrop方法 但我使用触摸而不是鼠标事件来做到这一点 我的网格 我正在拖动 的 XAML 如下
  • 如果 proxy_pass 响应中存在 etag,则禁用 gzip

    我是 Nginx 新手 如果 proxy pass 返回 ETag 标头 是否有办法禁用 gzip I E gzip on location foo bar proxy pass http server 123 if upstream ht
  • 通过 try() 之类的方法使 R 命令超时

    我正在并行运行大量迭代 某些迭代比其他迭代花费的时间要长得多 例如 100 倍 我想将这些超时 但我不想深入研究函数 称为 fun c 背后的 C 代码来完成繁重的工作 我希望有类似于 try 的东西 但有一个 time out 选项 然后
  • 最新的 OpenGL 教程或 C++ 书籍 [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • Websphere 中的 NoClassDefFoundError — 存在 JAR

    我有一个简单的 Spring MVC 应用程序 它从 LDAP 服务器查找一些用户详细信息 并使用 JSP 打印出一个简单的 HTML 页面 该应用程序在 Tomcat 6 上运行良好 它使用 Spring LDAP 1 3 1 和 LDA
  • 将变量传递到 CURLOPT_POSTFIELDS C++

    我正在尝试将变量传递到CURLOPT POSTFIELDS 我当前的代码 size t curl write void ptr size t size size t nmemb void stream std string cmd stat
  • 有没有办法询问 iOS 视图的哪个子视图具有第一响应者状态? [复制]

    这个问题在这里已经有答案了 在 Mac OS X 中 您可以这样找到第一响应者 self window firstResponder 在iOS中有什么方法可以做到这一点吗 或者您是否需要枚举子控件并发送isFirstResponder给每一
  • 如何使用 eclipse Nsight 仅使用一个 GPU 调试 CUDA

    我收到错误 所有 cuda 设备均用于显示 在调试时无法使用 使用Ubuntu 有没有什么方法可以使用 Nsight eclipse 仅使用一个 GPU 进行调试 我见过类似的解决方案 sudo 服务 lightdm 停止 杀死 X 但这也
  • 此版本的ChromeDriver仅支持Chrome版本93

    我有一个 Angular 项目 它使用 puppeteer 运行 Karma 偶尔会出现以下错误 11 13 43 E launcher session not created This version of ChromeDriver on
  • 如何简化三次贝塞尔曲线?

    我有一条三次贝塞尔曲线 由许多段组成 左图 它有一些粗糙的曲率 我需要让它像右图一样平滑 这个问题有点像 降噪 我该如何实现呢 有类似的线程here https stackoverflow com questions 3497694 sim
  • 在 C# 中打印到 LPT1

    如何在 C 中使用文件 LPT1 直接打印到点阵打印机 我用 fopen 在 C 上做到了这一点 但我不知道如何在 c 中做到这一点 非常感谢 在 Windows 中将打印机设置为 通用 仅文本 然后打印到它 这是我用来打印到具有自己的编码