2011-01-14 31 views
2

直接命令LPT並口如DOS,我們可以這樣做:發送打印使用C#.NET

ECHO MESSAGE>LPT1 

如何才能實現在C#.NET是一回事嗎?

發送信息給COM1似乎很容易使用C#.NET。

LPT1端口怎麼樣?

我想發送Escape命令給熱敏打印機。

回答

2

在C#4.0和更高版本的可能,首先你需要使用CreateFile方法再打開連接到端口一個到該端口的文件流,最終寫入它。 這是一個示例類,它在打印機上寫入兩行LPT1

using Microsoft.Win32.SafeHandles; 
using System; 
using System.IO; 
using System.Runtime.InteropServices; 

namespace YourNamespace 
{ 
    public static class Print2LPT 
     { 
      [DllImport("kernel32.dll", SetLastError = true)] 
      static extern SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess,uint dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); 

      public static bool Print() 
      { 
       string nl = Convert.ToChar(13).ToString() + Convert.ToChar(10).ToString(); 
       bool IsConnected= false; 

       string sampleText ="Hello World!" + nl + 
       "Enjoy Printing...";  
       try 
       { 
        Byte[] buffer = new byte[sampleText.Length]; 
        buffer = System.Text.Encoding.ASCII.GetBytes(sampleText); 

        SafeFileHandle fh = CreateFile("LPT1:", FileAccess.Write, 0, IntPtr.Zero, FileMode.OpenOrCreate, 0, IntPtr.Zero); 
        if (!fh.IsInvalid) 
        { 
         IsConnected= true;      
         FileStream lpt1 = new FileStream(fh,FileAccess.ReadWrite); 
         lpt1.Write(buffer, 0, buffer.Length); 
         lpt1.Close(); 
        } 

       } 
       catch (Exception ex) 
       { 
        string message = ex.Message; 
       } 

       return IsConnected; 
      } 
     } 
} 

假設您的打印機所連接的端口LPT1上,如果不是你將需要調整CreateFile方法來匹配您正在使用的端口。

你可以用下面的行

Print2LPT.Print(); 

任何地方調用該方法在程序中,我認爲這是最短的,最有效的解決您的問題。