public const short FILE_ATTRIBUTE_NORMAL = 0x80;
public const short INVALID_HANDLE_VALUE = -1;
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
public const uint CREATE_NEW = 1;
public const uint CREATE_ALWAYS = 2;
public const uint OPEN_EXISTING = 3;
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
public string SendCMDToLPT1()
{
try
{
IntPtr ptr = CreateFile("LPT1", GENERIC_WRITE, 0,
IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (ptr.ToInt32() == -1)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
else
{
FileStream lpt = new FileStream(ptr, FileAccess.ReadWrite);
Byte[] buffer = new Byte[5];
//0x1B, 0x70, 0x00,0x16,0x16
buffer[0] = 0x1B;
buffer[1] = 0x70;
buffer[2] = 0x00;
buffer[3] = 0x16;
buffer[4] = 0x16;
lpt.Write(buffer, 0, buffer.Length);
lpt.Close();
}
return "";
}
catch (Exception e)
{
return "" + e.Message.ToString();
}
}
以上是我操作并口的代码。在winform工程下这个是很好用的。
后来封装到ActiveX,里面。用IE调用的时候。
IntPtr ptr = CreateFile("LPT1", GENERIC_WRITE, 0,
IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
运行到这个句话的时候异常。
请教各位大侠!
权限不足,ActiveX没有操作lpt1的权限,lpt1相当于文件,需要给浏览器提权,还要设置安全等级为低才行。
先查看错误信息,是否为权限问题,IE运行在保护模式下,权限比较低,很多目录,设备等都不能访问
把所有的安全提示都关了