日期:2014-05-18  浏览次数:20945 次

关于调用API函数CreateFile打开LPT1端口的问题!!急盼解答!
private const uint GENERIC_READ = 0x80000000;
  private const uint GENERIC_WRITE = 0x40000000;
  private const uint OPEN_EXISTING = 3;

  [System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]
  private static extern SafeFileHandle CreateFile
  (
  string FileName, // file name
  uint DesiredAccess, // access mode
  uint ShareMode, // share mode
  uint SecurityAttributes, // Security Attributes
  uint CreationDisposition, // how to create
  uint FlagsAndAttributes, // file attributes
  int hTemplateFile // handle to template file
  );

  private void button7_Click(object sender, EventArgs e)
  {
  try
  {
  SafeFileHandle handle = CreateFile("LPT1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  if (handle.IsInvalid)
  {
  MessageBox.Show("没有连接打印机或者打印机端口不是LPT1", "提示窗口");
  return;
  }
  handle.Close();
  }
  catch (Exception Error) { MessageBox.Show(Error.Message, "错误提示"); }
  }
请问一下,为什么handle.IsInvalid不管LTP1端口有没有打印机,都是false呢?恳请各位解答!!!!我机器上只安装了office2003自带的虚拟打印机.

------解决方案--------------------
office2003自带的虚拟打印机.用的不是LPT 是 虚拟接口 Local Port 

 [System.Runtime.InteropServices.DllImport("kernel32", SetLastError = true)]
private static extern IntPtr CreateFile
(
string FileName, // file name 
uint DesiredAccess, // access mode 
uint ShareMode, // share mode 
uint SecurityAttributes, // Security Attributes 
uint CreationDisposition, // how to create 
uint FlagsAndAttributes, // file attributes 
int hTemplateFile // handle to template file 
);

返回的 IntPtr 为-1 没有打开接口
------解决方案--------------------
不管你接不接打印机,只要存在lpt端口,就可以打开
但是你可以通过对端口进行状态查询,来大概获知是否连接了设备

如果你是要打开指定打印机的,则可以通过调用打印方面的函数,直接取得某个名字的打印机的DC
------解决方案--------------------
添加虚拟打印机Microsoft Office Document Image Writer 

控制面板→打印机和传真→添加打印机→下一步→选择“连接到此计算机的本地打印机”→取消勾选“自动检测并安装即插即用打印机”→下一步→“使用以下端口”中选择“Microsoft Document Imaging Writer Port(Local)”→下一步→厂商选择“Generic”→打印机选择“Generic/Text Only”→点击“下一步”直到完成。

右击刚添加的打印机→属性→高级→“驱动程序”选“Microsoft Office Document Image Writer”→应用→常规→打印首选项→高级→“输出格式”选择“MDI”并勾选“压缩文档中的图像”→确定→确定。